孤儿进程和僵尸进程

从网上整理了一些关于孤儿和僵尸进程的资料,非常感谢大家的共享,因为内容较多,所以就不在明显的地方转载出处了,对此感到非常抱歉。

再次感谢你们的努力工作。

孤儿进程和僵尸进程[详解]

 (2014-02-27 19:32:12)


一、定义:什么是孤儿进程和僵尸进程
 

   僵尸进程:一个子进程在其父进程还没有调用wait()或waitpid()的情况下退出。这个子进程就是僵尸进程。
   孤儿进程:一个父进程退出,而它的一个或多个子进程还在运行,那么那些子进程将成为孤儿进程。孤儿进程将被init进程(进程号为1)所收养,并由init进程对它们完成状态收集工作。
注:
    僵尸进程将会导致资源浪费,而孤儿则不会。

 

子进程持续10秒钟的僵尸状态(EXIT_ZOMBIE)
------------------------------------------------------

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #include <sys/types.h>  
  2. #include <unistd.h>  
  3. #include <stdio.h>  
  4. #include <stdlib.h>  
  5.   
  6. main()  
  7. {  
  8.     pid_t pid;  
  9.     pid = fork();  
  10.     if(pid < 0)  
  11.         printf("error occurred!\n");  
  12.     else if(pid == 0) {  
  13.         printf("Hi father! I'm a ZOMBIE\n");  
  14.         exit(0);      //(1)  
  15.     }  
  16.     else {  
  17.         sleep(10);  
  18.         wait(NULL);   //(2)  
  19.     }  
  20. }  


(1) 向父进程发送SIGCHILD信号
(2) 父进程处理SIGCHILD信号

执行exit()时根据其父进程的状态决定自己的状态:
    如果父进程已经退出(没有wait),则该子进程将会成为孤儿进程过继给init进程
    如果其父进程还没有退出,也没有wait(),那么该进程将向父进程发送SIGCHILD信号,进入僵尸状态等待父进程为其收尸。如果父进程一直没有执行wait(),那么该子进程将会持续处于僵尸状态。


子进程将成为孤儿进程
------------------------------------------------------

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #include <sys/types.h>  
  2. #include <unistd.h>  
  3. #include <stdio.h>  
  4. #include <stdlib.h>  
  5.   
  6. main()  
  7. {  
  8.     pid_t pid;  
  9.     pid = fork();  
  10.     if(pid < 0)  
  11.         printf("error occurred!\n");  
  12.     else if(pid == 0) {  
  13.         sleep(6);  
  14.         printf("I'm a orphan\n");  
  15.         exit(0);  
  16.     }  
  17.     else {  
  18.         sleep(1);  
  19.         printf("Children Bye!\n");  
  20.     }  
  21. }  
  22.   
  23. # ./a.out  
  24. Children Bye!  
  25. # I'm a orphan  


(回车后将会进入#)
#
二、影响:
僵尸进程会占用系统资源,如果很多,则会严重影响服务器的性能
孤儿进程不会占用系统资源
处理流程:
只要父进程不等wait(sys/wait.h)子进程,子进程都将成为孤魂野鬼zombie(zombie),unix中默认父进程总是想看子进程死后的状态 
  if  父进程比子进程先退出 
    子进程将被init(id   =   1)收养,最后的结果是zombie子进程彻底再见,系统资源释放 
  else   
      { 
        子进程的zombie将一直存在,系统资源占用... 
        if   父进程dead   
            子进程将被init(id   =   1)收养,最后的结果是zombie子进程彻底再见,系统资源释放 
  
      else   类似的子进程zombie越来越多,系统就等死了!!! 
    } 
三、如何防止僵尸进程
首先明白如何产生僵尸进程:
1、子进程结束后向父进程发出SIGCHLD信号,父进程默认忽略了它
2、父进程没有调用wait()或waitpid()函数来等待子进程的结束
第一种方法:  捕捉SIGCHLD信号,并在信号处理函数里面调用wait函数

转贴Richard Steven的Unix Network Programming代码

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. int main(int argc, char **argv)  
  2. {  
  3.                 ...  
  4.         Signal(SIGCHLD, sig_chld);  
  5.                 for(;  
  6.                 }  
  7.                 ...  
  8. }  
  9.   
  10. void sig_chld(int signo)  
  11. {  
  12.         pid_t        pid;  
  13.         int         stat;  
  14.   
  15.         while ( (pid = waitpid(-1, &stat, WNOHANG)) >; 0)  
  16.                 printf("child %d terminated\n", pid);  
  17.         return;  
  18. }  


第二种方法:两次fork():转载
在《Unix 环境高级编程》里关于这个在8.6节有非常清楚的说明。

实例
回忆一下8 . 5节中有关僵死进程的讨论。如果一个进程要fork一个子进程,但不要求它等待子进程终止,也不希望子进程处于僵死状态直到父进程终止,实现这一要求的诀窍是调用fork两次。程序8 - 5实现了这一点。在第二个子进程中调用sleep以保证在打印父进程ID时第一个子进程已终止。在fork之后,父、子进程都可继续执行——我们无法预知哪一个会先执行。如果不使第二个子进程睡眠,则
在fork之后,它可能比其父进程先执行,于是它打印的父进程ID将是创建它的父进程,而不是init进程(进程ID1)。

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #include        <sys/types.h>  
  2. #include        <sys/wait.h>  
  3. #include        "ourhdr.h"  
  4.   
  5. int main(void)  
  6. {  
  7.         pid_t        pid;  
  8.   
  9.         if ( (pid = fork()) < 0)  
  10.                 err_sys("fork error");  
  11.         else if (pid == 0) {                 
  12.                 if ( (pid = fork()) < 0)  
  13.                         err_sys("fork error");  
  14.                 else if (pid > 0)  
  15.                         exit(0);         
  16.   
  17.                  
  18.   
  19.                 sleep(2);  
  20.                 printf("second child, parent pid = %d\n", getppid());  
  21.                 exit(0);  
  22.         }  
  23.   
  24.         if (waitpid(pid, NULL, 0) != pid)         
  25.                 err_sys("waitpid error");  
  26.   
  27.          
  28.   
  29.         exit(0);  
  30. }  
  31. //avoid zombie process by forking twice  



为何要fork()两次来避免产生僵尸进程?  

      当我们只fork()一次后,存在父进程和子进程。这时有两种方法来避免产生僵尸进程:

·         父进程调用waitpid()等函数来接收子进程退出状态。

·         父进程先结束,子进程则自动托管到Init进程(pid = 1)。

      目前先考虑子进程先于父进程结束的情况:     

·         若父进程未处理子进程退出状态,在父进程退出前,子进程一直处于僵尸进程状态。

·         若父进程调用waitpid()(这里使用阻塞调用确保子进程先于父进程结束)来等待子进程结束,将会使父进程在调用waitpid()后进入睡眠状态,只有子进程结束父进程的waitpid()才会返回。 如果存在子进程结束,但父进程还未执行到waitpid()的情况,那么这段时期子进程也将处于僵尸进程状态。

      由此,可以看出父进程与子进程有父子关系,除非保证父进程先于子进程结束或者保证父进程在子进程结束前执行waitpid(),子进程均有机会成为僵尸进程。那么如何使父进程更方便地创建不会成为僵尸进程的子进程呢?这就要用两次fork()了。

      父进程一次fork()后产生一个子进程随后立即执行waitpid(子进程pid, NULL, 0)来等待子进程结束,然后子进程fork()后产生孙子进程随后立即exit(0)。这样子进程顺利终止(父进程仅仅给子进程收尸,并不需要子进程的返回值),然后父进程继续执行。这时的孙子进程由于失去了它的父进程(即是父进程的子进程),将被转交给Init进程托管。于是父进程与孙子进程无继承关系了,它们的父进程均为Init,Init进程在其子进程结束时会自动收尸,这样也就不会产生僵尸进程了。

fork两次如何避免僵尸进程 (2009-07-09 20:14) 转载

在fork()/execve()过程中,假设子进程结束时父进程仍存在,而父进程fork()之前既没安装SIGCHLD 信号处理函数调用waitpid()等待子进程结束,又没有显式忽略该信号,则子进程成为僵尸进程,无法正常结束,此时即使是root身份kill-9也不能杀死僵尸进程。补救办法是杀死僵尸进程的父进程(僵尸进程的父进程必然存在),僵尸进程成为"孤儿进程",过继给1号进程init,init始终会负责清理僵尸进程。

怎样来清除僵尸进程:
1.改写父进程,在子进程死后要为它收尸。具体做法是接管SIGCHLD信号。子进程死后,会发送SIGCHLD信号给父进程,父进程收到此信号后,执行 waitpid()函数为子进程收尸。这是基于这样的原理:就算父进程没有调用wait,内核也会向它发送SIGCHLD消息,尽管对的默认处理是忽略,如果想响应这个消息,可以设置一个处理函数。
2.把父进程杀掉。父进程死后,僵尸进程成为"孤儿进程",过继给1号进程init,init始终会负责清理僵尸进程.它产生的所有僵尸进程也跟着消失。
3.调用fork两次。

如何产生僵死进程:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. #include <sys/types.h>  
  2. #include <unistd.h>  
  3. #include <stdio.h>  
  4. #include <stdlib.h>  
  5.   
  6. int main(int argc, char **argv)  
  7. {  
  8. if (0 == fork()) {  
  9. printf("In the child process:%d\n", getpid());  
  10. } else {  
  11. printf("In the parent process:%d\n", getpid());  
  12. sleep(10);  
  13. exit(0);  
  14. }  
  15. printf("Pid:%d\n", getpid());  
  16. return 0;  
  17. }  
  18.   
  19.    
  20.   
  21. 如何避免:  
  22.   
  23. 若调用成功则返回清理掉的子进程id,若调用出错则返回-1。父进程调用wait或waitpid时可能会:  
  24.   
  25.   
  26. 阻塞(如果它的所有子进程都还在运行)。  
  27. 带子进程的终止信息立即返回(如果一个子进程已终止,正等待父进程读取其终止信息)。  
  28. 出错立即返回(如果它没有任何子进程)。  
  29. 这两个函数的区别是:  
  30.   
  31.   
  32. 如果父进程的所有子进程都还在运行,调用wait将使父进程阻塞,而调用waitpid时如果在options参数中指定WNOHANG可以使父进程不阻塞而立即返回0。  
  33. wait等待第一个终止的子进程,而waitpid可以通过pid参数指定等待哪一个子进程。  
  34. 可见,调用wait和waitpid不仅可以获得子进程的终止信息,还可以使父进程阻塞等待子进程终止,起到进  
  35.   
  36. #include <sys/types.h>  
  37. #include <sys/wait.h>  
  38. #include <unistd.h>  
  39. #include <stdio.h>  
  40. #include <stdlib.h>  
  41. int main(void)  
  42. {  
  43.  pid_t pid;  
  44.  pid = fork();  
  45.  if (pid < 0) {  
  46.   perror("fork failed");  
  47.   exit(1);  
  48.  }  
  49.  if (pid == 0) {  
  50.   int i;  
  51.   for (i = 3; i > 0; i--) {  
  52.    printf("This is the child\n");  
  53.    sleep(1);  
  54.   }  
  55.   exit(3);  
  56.  } else {  
  57.   int stat_val;  
  58.   waitpid(pid, &stat_val, 0);  
  59.   if (WIFEXITED(stat_val))  
  60.    printf("Child exited with code %d\n", WEXITSTATUS(stat_val));  
  61.   else if (WIFSIGNALED(stat_val))  
  62.    printf("Child terminated abnormally, signal %d\n", WTERMSIG(stat_val));  
  63.  }  
  64.  return 0;  
  65. }  
  66. 2 处理信号:  
  67. #include <sys/types.h>  
  68. #include <unistd.h>  
  69. #include <stdio.h>  
  70. #include <stdlib.h>  
  71. #include<sys/wait.h>  
  72.   
  73. void proc_child(int SIGNO)  
  74. {  
  75. int pid = -1;  
  76. int stat;  
  77. pid = waitpid(-1, &stat, WNOHANG);  
  78. }  
  79.   
  80. int main(int argc, char **argv)  
  81. {  
  82. signal(SIGCHLD, proc_child);  
  83. if (0 == fork()) {  
  84. printf("In the child process:%d\n", getpid());  
  85. } else {  
  86. printf("In the parent process:%d\n", getpid());  
  87. sleep(10);  
  88. exit(0);  
  89. }  
  90. printf("Pid:%d\n", getpid());  
  91. return 0;  
  92. }  
  93.   
  94. 3 忽略信号  
  95. int main(int argc, char **argv)  
  96. {  
  97. signal(SIGCHLD, SIG_IGN); //加入此句即可,忽略SIGCHLD信号  
  98. if (0 == fork()) {  
  99. printf("In the child process:%d\n", getpid());  
  100. } else {  
  101. printf("In the parent process:%d\n", getpid());  
  102. sleep(10);  
  103. exit(0);  
  104. }  
  105. printf("Pid:%d\n", getpid());  
  106. return 0;  
  107. }  
  108. 4 apue上的fork两次:  
  109.   
  110. fork两次在防止僵死方面来说,就是因为儿子进程先退出,孙子进程就被init接管了,实际上与最初的父进程脱离了关系,就不会僵死了。  
  111.   
  112.   
  113. #include <stdio.h>  
  114. #include <sys/wait.h>  
  115. #include <sys/types.h>  
  116. #include <unistd.h>  
  117. int main(void)     
  118. {     
  119.    pid_t pid;     
  120.     
  121.     if ((pid = fork()) < 0)     
  122.     {     
  123.         fprintf(stderr,"Fork error!\n");     
  124.         exit(-1);     
  125.     }     
  126.     else if (pid == 0) /* first child */    
  127.     {      
  128.         if ((pid = fork()) < 0)     
  129.         {      
  130.             fprintf(stderr,"Fork error!\n");     
  131.             exit(-1);     
  132.         }     
  133.         else if (pid > 0)     
  134.             exit(0); /* parent from second fork == first child */    
  135.         /*    
  136.          * We're the second child; our parent becomes init as soon    
  137.          * as our real parent calls exit() in the statement above.    
  138.          * Here's where we'd continue executing, knowing that when    
  139.          * we're done, init will reap our status.    
  140.          */    
  141.         sleep(2);     
  142.         printf("Second child, parent pid = %d\n", getppid());     
  143.         exit(0);     
  144.     }     
  145.          
  146.     if (waitpid(pid, NULL, 0) != pid) /* wait for first child */    
  147.     {     
  148.         fprintf(stderr,"Waitpid error!\n");     
  149.         exit(-1);     
  150.     }     
  151.     
  152.     /*    
  153.      * We're the parent (the original process); we continue executing,    
  154.      * knowing that we're not the parent of the second child.    
  155.      */    
  156.     exit(0);     
  157. }     
  158. 5   
  159. static void  
  160. sig_child()  
  161. {  
  162.     waitpid(-1, NULL, 0);  
  163. }  


[...]
signal(SIGCHLD, sig_child)
sig_child这个函数有问题。这个函数的作用是每当有一个进程退出时,便会调用一次sig_child,sig_child便会调用
waitpid处理一个已退出的子进程。但是假如程序正在sig_child里面,这时又有另外一个子进程退出了,这时该怎么处理呢?处理的方法应该是不
会有另外一个sig_child响应,于是这时便有2个子进程退出了,但是sig_child只能处理一个,于是便有一个退出的子进程成了僵死进程了。

于是把sig_child改成:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. static void  
  2. sig_child()  
  3. {  
  4.     while (waitpid(-1, NULL, 0) > 0);  
  5. }  
  6.    


这样假如程序正在sig_child里面,这时又有另外n个子进程退出了,由于用了while,于是sig_child便会将所以退出的子进程“一网打尽”。

这是一种处理僵死进程的方法,另外还有2种:
signal(SIGCHLD, SIG_IGN);
忽略SIGCHLD信号,父进程不需要处理,直接把退出的子进程推给init进程处理。

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. struct sigaction    sa;  
  2. sa.sa_handler = SIG_IGN;  
  3. sa.sa_flags = SA_NOCLDWAIT;  
  4. sigemptyset(&sa.sa_mask);  
  5. if (sigaction(SIGCHLD, &sa, NULL) < 0) {  
  6.     exit(-1);  
  7. }  



谈谈守护进程与僵尸进程

分类: 技术分享2011-12-21 11:00 5376人阅读 评论(14) 收藏 举报

04年时维护的第一个商业服务就用了两次fork产生守护进程的做法,前两天在网上看到许多帖子以及一些unix书籍,认为一次fork后产生守护进程足够了,各有道理吧,不过多了一次fork到底是出于什么目的呢?

 

进程也就是task,看看内核里维护进程的数据结构task_struct,这里有两个成员:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. view plain  
  2.   
  3.   
  4. 1.  struct task_struct {    
  5.   
  6. 2.      volatile long state;    
  7.   
  8. 3.      int exit_state;    
  9.   
  10. 4.      ...    
  11.   
  12. 5.  }    




看看include/linux/sched.h里的value取值:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. view plain  
  2.   
  3.   
  4. 1.  #define TASK_RUNNING        0    
  5.   
  6. 2.  #define TASK_INTERRUPTIBLE  1    
  7.   
  8. 3.  #define TASK_UNINTERRUPTIBLE    2    
  9.   
  10. 4.  #define __TASK_STOPPED      4    
  11.   
  12. 5.  #define __TASK_TRACED       8    
  13.   
  14. 6.  /* in tsk->exit_state */    
  15.   
  16. 7.  #define EXIT_ZOMBIE     16    
  17.   
  18. 8.  #define EXIT_DEAD       32    
  19.   
  20. 9.  /* in tsk->state again */    
  21.   
  22. 10. #define TASK_DEAD       64    
  23.   
  24. 11. #define TASK_WAKEKILL       128    
  25.   
  26. 12. #define TASK_WAKING     256    
  27.   
  28. 13. #define TASK_STATE_MAX      512    




可以看到,进程状态里除了大家都理解的running/interuptible/uninterruptible/stop等状态外,还有一个ZOMBIE状态,这个状态是怎么回事呢?

 

这是因为linux里的进程都属于一颗树,树的根结点是linux系统初始化结束阶段时启动的init进程,这个进程的pid是1,所有的其他进程都是它的子孙。除了init,任何进程一定有他的父进程,而父进程会负责分配(fork)、回收(wait4)它申请的进程资源。这个树状关系也比较健壮,当某个进程还在运行时,它的父进程却退出了,这个进程却没有成为孤儿进程,因为linux有一个机制,init进程会接管它,成为它的父进程。这也是守护进程的由来了,因为守护进程的其中一个要求就是希望init成为守护进程的父进程。

 

如果某个进程自身终止了,在调用exit清理完相关的内容文件等资源后,它就会进入ZOMBIE状态,它的父进程会调用wait4来回收这个task_struct,但是,如果父进程一直没有调用wait4去释放子进程的task_struct,问题就来了,这个task_struct谁来回收呢?永远没有人,除非父进程终止后,被init进程接管这个ZOMBIE进程,然后调用wait4来回收进程描述符。如果父进程一直在运行着,这个ZOMBIE会永远的占用系统资源,用KILL发任何信号量也不能释放它。这是很可怕的,因为服务器上可能会出现无数ZOMBIE进程导致机器挂掉。

 

来看看内核代码吧。进程在退出时执行sys_exit(C程序里在main函数返回会执行到),而它会调用do_exit,do_exit首先清理进程使用的资源,然后调用exit_notify方法,将进程置为僵尸ZOMBIE状态,决定是否要以init进程做为当前进程的父进程,最后通知当前进程的父进程:

kernel/exit.c

view plain

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. 1.  static void exit_notify(struct task_struct *tsk)    
  2.   
  3. 2.  {    
  4.   
  5. 3.      int state;    
  6.   
  7. 4.      struct task_struct *t;    
  8.   
  9. 5.      struct list_head ptrace_dead, *_p, *_n;    
  10.   
  11. 6.      
  12.   
  13. 7.      if (signal_pending(tsk) && !tsk->signal->group_exit    
  14.   
  15. 8.          && !thread_group_empty(tsk)) {    
  16.   
  17. 9.          /*   
  18.   
  19. 10.          * This occurs when there was a race between our exit   
  20.   
  21. 11.          * syscall and a group signal choosing us as the one to   
  22.   
  23. 12.          * wake up.  It could be that we are the only thread   
  24.   
  25. 13.          * alerted to check for pending signals, but another thread   
  26.   
  27. 14.          * should be woken now to take the signal since we will not.   
  28.   
  29. 15.          * Now we'll wake all the threads in the group just to make   
  30.   
  31. 16.          * sure someone gets all the pending signals.   
  32.   
  33. 17.          */    
  34.   
  35. 18.         read_lock(&tasklist_lock);    
  36.   
  37. 19.         spin_lock_irq(&tsk->sighand->siglock);    
  38.   
  39. 20.         for (t = next_thread(tsk); t != tsk; t = next_thread(t))    
  40.   
  41. 21.             if (!signal_pending(t) && !(t->flags & PF_EXITING)) {    
  42.   
  43. 22.                 recalc_sigpending_tsk(t);    
  44.   
  45. 23.                 if (signal_pending(t))    
  46.   
  47. 24.                     signal_wake_up(t, 0);    
  48.   
  49. 25.             }    
  50.   
  51. 26.         spin_unlock_irq(&tsk->sighand->siglock);    
  52.   
  53. 27.         read_unlock(&tasklist_lock);    
  54.   
  55. 28.     }    
  56.   
  57. 29.     
  58.   
  59. 30.     write_lock_irq(&tasklist_lock);    
  60.   
  61. 31.     
  62.   
  63. 32.     /*   
  64.   
  65. 33.      * This does two things:   
  66.   
  67. 34.      *   
  68.   
  69. 35.      * A.  Make init inherit all the child processes   
  70.   
  71. 36.      * B.  Check to see if any process groups have become orphaned   
  72.   
  73. 37.      *  as a result of our exiting, and if they have any stopped   
  74.   
  75. 38.      *  jobs, send them a SIGHUP and then a SIGCONT.  (POSIX 3.2.2.2)   
  76.   
  77. 39.      */    
  78.   
  79. 40.     
  80.   
  81. 41.     INIT_LIST_HEAD(&ptrace_dead);    
  82.   
  83. 42.     <strong><span style="color:#ff0000;">forget_original_parent(tsk, &ptrace_dead);</span></strong>    
  84.   
  85. 43.     BUG_ON(!list_empty(&tsk->children));    
  86.   
  87. 44.     BUG_ON(!list_empty(&tsk->ptrace_children));    
  88.   
  89. 45.     
  90.   
  91. 46.     /*   
  92.   
  93. 47.      * Check to see if any process groups have become orphaned   
  94.   
  95. 48.      * as a result of our exiting, and if they have any stopped   
  96.   
  97. 49.      * jobs, send them a SIGHUP and then a SIGCONT.  (POSIX 3.2.2.2)   
  98.   
  99. 50.      *   
  100.   
  101. 51.      * Case i: Our father is in a different pgrp than we are   
  102.   
  103. 52.      * and we were the only connection outside, so our pgrp   
  104.   
  105. 53.      * is about to become orphaned.   
  106.   
  107. 54.      */    
  108.   
  109. 55.          
  110.   
  111. 56.     t = tsk->real_parent;    
  112.   
  113. 57.         
  114.   
  115. 58.     if ((process_group(t) != process_group(tsk)) &&    
  116.   
  117. 59.         (t->signal->session == tsk->signal->session) &&    
  118.   
  119. 60.         will_become_orphaned_pgrp(process_group(tsk), tsk) &&    
  120.   
  121. 61.         has_stopped_jobs(process_group(tsk))) {    
  122.   
  123. 62.         __kill_pg_info(SIGHUP, (void *)1, process_group(tsk));    
  124.   
  125. 63.         __kill_pg_info(SIGCONT, (void *)1, process_group(tsk));    
  126.   
  127. 64.     }    
  128.   
  129. 65.     
  130.   
  131. 66.     /* Let father know we died    
  132.   
  133. 67.      *   
  134.   
  135. 68.      * Thread signals are configurable, but you aren't going to use   
  136.   
  137. 69.      * that to send signals to arbitary processes.    
  138.   
  139. 70.      * That stops right now.   
  140.   
  141. 71.      *   
  142.   
  143. 72.      * If the parent exec id doesn't match the exec id we saved   
  144.   
  145. 73.      * when we started then we know the parent has changed security   
  146.   
  147. 74.      * domain.   
  148.   
  149. 75.      *   
  150.   
  151. 76.      * If our self_exec id doesn't match our parent_exec_id then   
  152.   
  153. 77.      * we have changed execution domain as these two values started   
  154.   
  155. 78.      * the same after a fork.   
  156.   
  157. 79.      *     
  158.   
  159. 80.      */    
  160.   
  161. 81.         
  162.   
  163. 82.     if (tsk->exit_signal != SIGCHLD && tsk->exit_signal != -1 &&    
  164.   
  165. 83.         ( tsk->parent_exec_id != t->self_exec_id  ||    
  166.   
  167. 84.           tsk->self_exec_id != tsk->parent_exec_id)    
  168.   
  169. 85.         && !capable(CAP_KILL))    
  170.   
  171. 86.         tsk->exit_signal = SIGCHLD;    
  172.   
  173. 87.     
  174.   
  175. 88.     
  176.   
  177. 89.     /* If something other than our normal parent is ptracing us, then   
  178.   
  179. 90.      * send it a SIGCHLD instead of honoring exit_signal.  exit_signal   
  180.   
  181. 91.      * only has special meaning to our real parent.   
  182.   
  183. 92.      */    
  184.   
  185. 93.     if (tsk->exit_signal != -1 && thread_group_empty(tsk)) {    
  186.   
  187. 94.         int signal = tsk->parent == tsk->real_parent ? tsk->exit_signal : SIGCHLD;    
  188.   
  189. 95.         <span style="color:#ff0000;">do_notify_parent(tsk, signal);</span>    
  190.   
  191. 96.     } else if (tsk->ptrace) {    
  192.   
  193. 97.         do_notify_parent(tsk, SIGCHLD);    
  194.   
  195. 98.     }    
  196.   
  197. 99.     
  198.   
  199. 100.     <span style="color:#ff0000;"><strong>state = EXIT_ZOMBIE;</strong></span>    
  200.   
  201. 101.     if (tsk->exit_signal == -1 && tsk->ptrace == 0)    
  202.   
  203. 102.         state = EXIT_DEAD;    
  204.   
  205. 103.     tsk->exit_state = state;    
  206.   
  207. 104.     
  208.   
  209. 105.     /*   
  210.   
  211. 106.      * Clear these here so that update_process_times() won't try to deliver   
  212.   
  213. 107.      * itimer, profile or rlimit signals to this task while it is in late exit.   
  214.   
  215. 108.      */    
  216.   
  217. 109.     tsk->it_virt_value = 0;    
  218.   
  219. 110.     tsk->it_prof_value = 0;    
  220.   
  221. 111.     
  222.   
  223. 112.     write_unlock_irq(&tasklist_lock);    
  224.   
  225. 113.     
  226.   
  227. 114.     list_for_each_safe(_p, _n, &ptrace_dead) {    
  228.   
  229. 115.         list_del_init(_p);    
  230.   
  231. 116.         t = list_entry(_p,struct task_struct,ptrace_list);    
  232.   
  233. 117.         release_task(t);    
  234.   
  235. 118.     }    
  236.   
  237. 119.     
  238.   
  239. 120.     /* If the process is dead, release it - nobody will wait for it */    
  240.   
  241. 121.     if (state == EXIT_DEAD)    
  242.   
  243. 122.         release_task(tsk);    
  244.   
  245. 123.     
  246.   
  247. 124.     /* PF_DEAD causes final put_task_struct after we schedule. */    
  248.   
  249. 125.     preempt_disable();    
  250.   
  251. 126.     tsk->flags |= PF_DEAD;    
  252.   
  253. 127. }    





大家可以看到这段内核代码的注释非常全。forget_original_parent这个函数还会把该进程的所有子孙进程重设父进程,交给init进程接管。

 

回过头来,看看为什么守护进程要fork两次。这里有一个假定,父进程生成守护进程后,还有自己的事要做,它的人生意义并不只是为了生成守护进程。这样,如果父进程fork一次创建了一个守护进程,然后继续做其它事时阻塞了,这时守护进程一直在运行,父进程却没有正常退出。如果守护进程因为正常或非正常原因退出了,就会变成ZOMBIE进程。

如果fork两次呢?父进程先fork出一个儿子进程,儿子进程再fork出孙子进程做为守护进程,然后儿子进程立刻退出,守护进程被init进程接管,这样无论父进程做什么事,无论怎么被阻塞,都与守护进程无关了。所以,fork两次的守护进程很安全,避免了僵尸进程出现的可能性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值