I have situation where one parent process may spawn many child processes. What I want to achieve is that if parent process is killed or if it exits, then all it's children should terminate together with parent.
In the post (link below) I have found suggestion to archive this by making parent process a group leader.
If I understand it right this is also the main purpose of process groups. Am I right?
Post also mentions prctl(PR_SET_PDEATHSIG, SIGHUP); and some other methods, but they are ether OS specific or otherwise don't seam so elegant.
I have written a small demo to try to understand things better, but it doesn't work the way I expect. What am I doing wrong?
//https://www.andrew.cmu.edu/course/15-310/applications/homework/homework4/terminalgroups1.html
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <stddef.h>
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/termios.h>
int main()
{
int status;
int cpid;
int ppid;
ppid = getpid();
printf("parent: %d\n", ppid);
if (!(cpid=fork()))
{
printf("child: %d\n", getpid());
if(setpgid(0,ppid) == -1)
printf("child setpgid errno %s\n", strerror(errno));
else
printf("child gid %d\n", getpgid(0));
pause();
printf("child exited\n");
exit (-1);
}
if (cpid < 0)
exit(-1);
setpgid(0, ppid);
if(setpgid(0,0) == -1)
printf("parent setpgid erno %s\n", strerror(errno));
else
printf("parrent gid %d\n", getpgid(0));
sleep(7);
printf("parent exit\n");
exit(0);
}
This post relates to suggestion made in : * How to make child process die after parent exits?