Last active
September 19, 2020 21:35
-
-
Save leehambley/5589953 to your computer and use it in GitHub Desktop.
Handle SIGCHLD in C to be notified when a child process has exited. via http://www.linuxquestions.org/questions/programming-9/how-a-father-process-know-which-child-process-send-the-signal-sigchld-266290/
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
// Via http://www.linuxquestions.org/questions/programming-9/how-a-father-process-know-which-child-process-send-the-signal | |
#include <stdio.h> | |
#include <signal.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
void handler(int sig) | |
{ | |
pid_t pid; | |
pid = wait(NULL); | |
printf("Pid %d exited.\n", pid); | |
} | |
int main(void) | |
{ | |
signal(SIGCHLD, handler); | |
if(!fork()) | |
{ | |
printf("Child pid is %d\n", getpid()); | |
exit(0); | |
} | |
printf("Parent pid is %d\n", getpid()); | |
getchar(); | |
return 0; | |
} |
very nice... simplistic mechanism to make handleres
fork() will return -1 when it fails, may be worth adding a comment or updating your code
Even better if you change the exit(0)
to return 0
you can exit the program more cleanly and you no longer have a dependency on stdlib.h
.
Even better if you change the exit(0) to return 0 you can exit the program more cleanly and you no longer have a dependency on stdlib.h.
True, it also saves about 100b
and a compiler warning.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In order the script to work you must inlucde also "#include <stdlib.h>"