我有一個父進程可能會產生許多子進程的情況。 我想要實現的是,如果父進程被終止或者它退出,那麼它所有的子進程應該與父進程一起終止。進程組中的進程是否應該在Unix/Linux中與其父進程一起終止?
在帖子中(下面的鏈接)我發現建議通過讓父進程成爲組長來歸檔這個建議。 如果我理解正確,這也是過程組的主要目的。我對嗎?
帖子中還提到了prctl(PR_SET_PDEATHSIG,SIGHUP);和其他一些方法,但它們是以太網操作系統特定的,否則沒有接縫那麼優雅。
我寫了一個小的演示,試圖更好地理解事物,但它並不按我期望的方式工作。我究竟做錯了什麼?
//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);
}
這篇文章涉及在由建議: * How to make child process die after parent exits?
*如何*它不按您期望的方式工作?你能指望什麼? –
父進程在7秒後終止,但子進程依然存在並且被init進程孤立。我希望孩子能夠收到一些信號,並與父母一起終止。 – user2979375
http://man7.org/linux/man-pages/man3/exit.3.html說,但我不知道這是否是在這種情況下是實際的: 如果該過程是會議的領導者,其控制終端是 該會話的控制終端,則該控制終端的前臺進程組中的每個進程被髮送一個SIGHUP信號,並且該終端與該會話取消關聯,允許它被新的控制進程獲取。 – user2979375