Linux-孤儿进程和僵死进程

文章目录

孤儿进程

概述

复制代码
父进程运行结束,子进程还在运行,此时,子进程就成了孤儿进程(Orphan Process)

每当出现一个孤儿进程的时候,内核就把孤儿进程的父进程设置为 init ,而 init 进程会循环地 wait() 它的已经退出的子进程。这样,当一个孤儿进程凄凉地结束了其生命周期的时候,init 进程就会代表党和政府出面处理它的一切善后工作。

因此孤儿进程并不会有什么危害。

c 复制代码
  1  #include <stdio.h>
  2  #include <string.h>
  3 #include <stdlib.h>
  4 
  5 #include <unistd.h>
  6 
  7 
  8 
  9 //孤儿进程
 10 
 11 int test01()
 12 {
 13     pid_t pid = -1;
 14 
 15     pid = fork();
 16     if(-1 == pid)
 17     {
 18         perror("fork"); 
 19         goto err0; 
 20     } 
 21     if(pid >0) 
 22     { 
 23         sleep(2); 
 24         printf("父进程退出 %d\n", getpid()); 
 25         exit(0); 
 26     } 
 27  
 28     while(1) 
 29     { 
 30         printf("子进程工作 %d...\n", getppid()); 
 31         sleep(1); 
 32     } 
 33  
 34     return 0; 
 35 err0: 
 36     return 1; 
 37 } 
 38 int main(void) 
 39 { 
 40     test01(); 
 41     return 0; 
 42 }

僵死进程

概述

进程终止,父进程尚未回收,子进程残留资源(PCB)存放于内核中,变成僵尸(Zombie)进程。

这样就会导致一个问题,如果进程不调用wait() 或 waitpid() 的话, 那么保留的那段信息就不会释放,其进程号就会一直被占用,但是系统所能使用的进程号是有限的,如果大量的产生僵尸进程,将因为没有可用的进程号而导致系统不能产生新的进程,此即为僵尸进程的危害,应当避免。

c 复制代码
  1 #include <stdio.h>
  2 #include <string.h>
  3 #include <stdlib.h>
  4 
  5 #include <unistd.h>
  6 
  7 
  8 
  9 int test01()
 10 {
 11     pid_t pid = -1;
 12 
 13     pid = fork();
 14     if(-1 == pid)
 15     {
 16         perror("fork");
 17         goto err0;
 18     }
 19 
 20     if(0 == pid)
 21     {
 22         printf("3s后子进程退出\n");
 23         sleep(3);
 24         printf("子进程退出...\n");
 25         exit(0);
 26     }
 27     else
 28     {
 29 
 30         sleep(3000);
 31     }
 32 
 33 
 34     return 0;
 35 err0:
 36     return 1;
 37 }
 38 
 39	int main()
 40	{
 41		test01();
 42		return 0;
 43	}