僵尸进程&孤儿进程

来源:互联网 发布:经济数据库都有什么 编辑:程序博客网 时间:2024/05/20 00:13

我们知道在unix/linux中,正常情况下,子进程是通过父进程创建的,子进程在创建新的进程。子进程的结束和父进程的运行是一个异步过程,即父进程永远无法预测子进程 到底什么时候结束。 当一个 进程完成它的工作终止之后,它的父进程需要调用wait()或者waitpid()系统调用取得子进程的终止状态。
僵尸进程
一个进程使用fork创建子进程,如果子进程退出,而父进程并没有调用wait或waitpid获取子进程的状态信息,那么子进程的进程描述符仍然保存在系统中。这种进程称之为僵死进程。

孤儿进程
一个父进程退出,而它的一个或多个子进程还在运行,那么那些子进程将成为孤儿进程。孤儿进程将被init进程(进程号为1)所收养,并由init进程对它们完成状态收集工作。

孤儿进程测试:

 #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> int main()  {      pid_t pid;      //创建一个进程     pid = fork();     //创建失败     if (pid < 0)     {         perror("fork error:");         exit(1);     }     //子进程     if (pid == 0)     {         printf("I am the child process.\n");         //输出进程ID和父进程ID         printf("pid: %d\tppid:%d\n",getpid(),getppid());         printf("I will sleep five seconds.\n");         //睡眠5s,保证父进程先退出         sleep(5);         printf("pid: %d\tppid:%d\n",getpid(),getppid());         printf("child process is exited.\n");     }     //父进程     else     {         printf("I am father process.\n");         //父进程睡眠1s,保证子进程输出进程id         sleep(1);         printf("father process is  exited.\n");     }     return 0; }

这里写图片描述

僵尸进程测试:

 #include <stdio.h> #include <unistd.h> #include <errno.h> #include <stdlib.h>  int main()  {      pid_t pid;      pid = fork();     if (pid < 0)    {         perror("fork error:");         exit(1);     }     else if (pid == 0)     {         printf("I am child process.I am exiting.\n");         exit(0);     }     printf("I am father process.I will sleep two seconds\n");     //等待子进程先退出     sleep(2);     //输出进程信息     system("ps -o pid,ppid,state,tty,command");     printf("father process is exiting.\n");     return 0; }

这里写图片描述

僵尸进程解决办法:通过信号量机制
子进程退出时向父进程发出SIGCHILD信号。在信号处理函数中调用wait进行处理僵尸进程

区分:
一个正常运行的子进程,如果此刻子进程退出,父进程没有及时调用wait或waitpid收回子进程的系统资源,该进程就是僵尸进程,如果系统收回了,就是正常退出,如果一个正常运行的子进程,父进程退出了但是子进程还在,该进程此刻是孤儿进程,被init收养,如果父进程是故意被杀掉,子进程做相应处理后就是守护进程

0 0
原创粉丝点击