Skip to content

Instantly share code, notes, and snippets.

@kgbook
Last active November 12, 2018 12:07
Show Gist options
  • Save kgbook/994b219e0e25055b474326b68e8bf5dd to your computer and use it in GitHub Desktop.
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
#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