Last active
November 12, 2018 12:07
-
-
Save kgbook/994b219e0e25055b474326b68e8bf5dd to your computer and use it in GitHub Desktop.
[atexit example]register a function to be called at normal process termination #atexit #interprocess
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 <iostream> | |
#include <cstdlib> | |
#include <unistd.h> | |
#include <cstring> | |
#include <cerrno> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
void parent_process_callback() { | |
std::cout <<__func__ <<", pid: " <<getpid() <<std::endl; | |
} | |
void child_process_callback() { | |
std::cout <<__func__ <<", pid: " <<getpid() <<std::endl; | |
} | |
int main(int argc, char **argv) { | |
sem_child = new Semaphore; | |
sem_parent = new Semaphore; | |
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: { | |
std::cout <<"parent process! pid:" <<getpid() <<std::endl; | |
atexit(parent_process_callback); | |
while (pid = waitpid(-1, nullptr, 0)) { | |
if (ECHILD == errno) { | |
break; | |
} | |
std::cout <<"[" <<__func__ <<":" <<__LINE__ <<"]" <<"child " <<pid <<" terminated!" <<std::endl; | |
} | |
break; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment