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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章