UNIX环境高级编程学习笔记:9_12 孤儿进程 孤儿进程组

为什么父进程死后 子进程没有被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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值