为什么父进程死后 子进程没有被init(pid =1)领养 却是被别的进程领养。
./orphan
name:parent pid = 10174, ppid = 19970, pgrp = 10174, tpgrp = 10174
name:child pid = 10176, ppid = 10174, pgrp = 10174, tpgrp = 10174
SIGHUP received,pid=10176
name:child pid = 10176, ppid = 18070, pgrp = 10174, tpgrp = 19970
read error 5 on controlling TTY
若父进程退出导致进程组成为孤儿进程组,且该进程组中有进程处于停止状态(收到SIGSTOP或SIGTSTP信号),SIGHUP信号会被发送到该进程组中的每一个进程。
源代码:
vim 9_12.c
1 #include "apue.h"
2 #include <errno.h>
3 static void sig_hup()
4 {
5 printf("SIGHUP received,pid=%ld\n",(long) getpid());
6 }
7
8 static void pr_ids(char *name)
9 {
10 printf("name:%s pid = %ld, ppid = %ld, pgrp = %ld, tpgrp = %ld\n",name,(long) getpid(), (long) getppid(), (long) getpgrp(), (long) tcgetpgrp(STDIN_FILENO));
11 }
12
13
14 int main()
15 {
16 char c;
17 pid_t pid;
18
19 pr_ids("parent");
20 if ( (pid = fork()) < 0){
21 err_sys("fork error");
22 }
23 if ( pid > 0 )
24 sleep(5);
25 else{
26 pr_ids("child");
27 signal(SIGHUP,sig_hup);
28 kill(getpid(),SIGTSTP);
29 pr_ids("child");
30 if (read(STDIN_FILENO,&c,1) != 1)
31 printf("read error %d on controlling TTY\n",errno);
32 }
33 exit(0);
34 }
运行结果:
./orphan
name:parent pid = 4168, ppid = 19970, pgrp = 4168, tpgrp = 4168
name:child pid = 4170, ppid = 4168, pgrp = 4168, tpgrp = 4168
SIGHUP received,pid=4170
name:child pid = 4170, ppid = 18070, pgrp = 4168, tpgrp = 19970
read error 5 on controlling TTY
./orphan
name:parent pid = 10174, ppid = 19970, pgrp = 10174, tpgrp = 10174
name:child pid = 10176, ppid = 10174, pgrp = 10174, tpgrp = 10174
SIGHUP received,pid=10176
name:child pid = 10176, ppid = 18070, pgrp = 10174, tpgrp = 19970
read error 5 on controlling TTY
后来查了一下 pid 18070 对应的进程名称。
ps -ef | grep 18070
root 18070 18070 0 Oct 18 ? 0:00 zsched
在linux上运行 没有问题。
gcc -Wall -ggdb3 -o aaa 9_12.c
./aaa
name:parent pid = 14063, ppid = 13965, pgrp = 14063, tpgrp = 14063
name:child pid = 14064, ppid = 14063, pgrp = 14063, tpgrp = 14063
SIGHUP received,pid=14064
name:child pid = 14064, ppid = 1, pgrp = 14063, tpgrp = 14063
read error 5 on controlling TTY