Last active
November 12, 2018 12:12
-
-
Save kgbook/56ddc557e5b29743fd09899f9ee9628e to your computer and use it in GitHub Desktop.
[interprocess semaphore example]interprocess semaphore example #interprocess #semaphore
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <csignal> | |
#include <sys/wait.h> | |
#include "SharedSemaphore.h" | |
pid_t parent_pid; | |
Semaphore *sem; | |
void parent_process_callback() { | |
std::cout <<__func__ <<", pid: " <<getpid() <<std::endl; | |
} | |
void child_process_callback() { | |
std::cout <<__func__ <<", pid: " <<getpid() <<std::endl; | |
} | |
static void sigint_handler(int32_t signo) { | |
std::cout <<__func__ <<", signo:" <<signo <<", pid:" <<getpid() <<std::endl; | |
if (parent_pid != getpid()) { | |
exit(0); | |
} | |
} | |
static void setup_sigint_handler() { | |
struct sigaction act; | |
act.sa_handler = sigint_handler; | |
sigemptyset(&act.sa_mask); | |
#if 0 | |
act.sa_flags = 0; | |
#else | |
act.sa_flags = SA_RESTART; /* Interrupted system call when sem_wait */ | |
#endif | |
sigaction(SIGINT, &act, NULL); | |
} | |
void reclaim_zombie_process() { | |
while (1) { | |
pid_t reclaim_pid = waitpid(child_pid, nullptr, 0); | |
if (reclaim_pid < 0) { | |
if (ECHILD == errno) { | |
std::cout <<__func__ <<", all child process terminated!" <<std::endl; | |
break; | |
} else { | |
std::cout <<__func__ <<", waitpid failed, " <<strerror(errno) <<std::endl; | |
continue; | |
} | |
} | |
std::cout <<__func__ <<", pid: " <<reclaim_pid <<" terminated!" <<std::endl; | |
} | |
} | |
int main(int argc, char **argv) { | |
sem_parent = new Semaphore("parent-process"); | |
setup_sigint_handler(); | |
pid_t pid = fork(); | |
switch (pid) { | |
case 0: { | |
std::cout <<"child process, pid:" <<getpid() <<std::endl; | |
atexit(child_process_callback); | |
break; | |
} | |
case -1: { | |
std::cerr <<"fork failed, " <<strerror(errno) <<std::endl; | |
break; | |
} | |
default: { | |
parent_pid = getpid(); | |
std::cout <<"parent process! pid:" <<parent_pid <<", child process id: " << pid <<std::endl; | |
atexit(parent_process_callback); | |
reclaim_zombie_process(); | |
break; | |
} | |
} | |
std::cout <<"semaphore value: " <<sem->getValue() <<std::endl; | |
sem->wait(); | |
std::cout <<"process " <<getpid() <<std::endl; | |
/* deinit here */ | |
std::cout <<"deinit done!" <<std::endl; | |
delete sem; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment