僵尸进程产生实例

为何会产生僵尸进程,和孤儿进程有何区别?

僵尸进程

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值