为何会产生僵尸进程,和孤儿进程有何区别?
僵尸进程
zombie process
子进程比父进程先结束,但父进程并有没有回收子进程占用的资源(比如调用waitpid()),那么子进程就成为一个僵尸进程。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
pid_t i = fork();
if(i == 0){
printf("this is child:%d\n", getpid());
exit(0);
}else{
printf("this is parent:%d, child:%d\n", getpid(), i);
sleep(30);
}
return 0;
}
子进程先结束,且父进程没有waitpid()回收,子进程就成为僵尸进程,等到父进程结束,僵尸进程也结束。
[root@localhost rg]# ./test
this is parent:31041, child:31042
this is child:31042
[root@localhost ~]# ps aux | grep Z+
root 31042 0.0 0.0 0 0 pts/0 Z+ 02:54 0:00 [test] <defunct>
root 31104 0.0 0.0 112836 2324 pts/2 S+ 02:54 0:00 grep --color=auto Z+
孤儿进程
父进程先退出,而它的一个或多个子进程还在运行,则这些子进程成为孤儿进程,会被1号进程收管。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
pid_t i = fork();
if(i == 0){
printf("this is child:%d\n", getpid());
sleep(30);
}else{
printf("this is parent:%d, child:%d\n", getpid(), i);
exit(0);
}
return 0;
}
此时子进程实为孤儿进程(orphan),其状态是S(可中断的睡眠状态)。
[root@localhost rg]# ./test1
this is parent:32629, child:32630
this is child:32630
[root@localhost ~]# ps aux | grep test
root 32630 0.0 0.0 4232 84 pts/0 S 02:56 0:00 ./test1
root 32778 0.0 0.0 112836 2260 pts/2 S+ 02:56 0:00 grep --color=auto test