Skip to content

Instantly share code, notes, and snippets.

@leehambley
Last active September 19, 2020 21:35
Show Gist options
  • Save leehambley/5589953 to your computer and use it in GitHub Desktop.
Save leehambley/5589953 to your computer and use it in GitHub Desktop.
// 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;
}
@hoenirvili
Copy link

In order the script to work you must inlucde also "#include <stdlib.h>"

@ballu1490
Copy link

very nice... simplistic mechanism to make handleres

@GothAck
Copy link

GothAck commented Dec 9, 2018

fork() will return -1 when it fails, may be worth adding a comment or updating your code

@ericcurtin
Copy link

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.

@leehambley
Copy link
Author

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