僵尸进程和孤儿进程

本文探讨了Linux操作系统中的两种特殊进程状态——僵尸进程和孤儿进程。僵尸进程是指父进程未等待子进程退出,子进程先结束,留下无法释放的资源。孤儿进程则是父进程在子进程之前结束,被init进程收养。通过示例代码展示了这两种进程状态的产生过程。
摘要由CSDN通过智能技术生成

僵尸进程:父进程不等待子进程退出,并且子进程先父进程退出,那么子进程变成僵尸进程

//运行以下代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
        int status;
        int i = 4;
        pid_t pid = fork();
        if(pid > 0)
        {
                while(1)
                {
                        printf("this is father pid:%d\n",getpid());
                        sleep(3);
                }
        }
        else if(pid == 0)
        {
                while(--i)
                {
                        printf("this is child pid:%d\n",getpid());
                        sleep(3);
                }
                exit(2);

        }
        return ;
}                                

打开终端:这边打开了两个终端在这里插入图片描述
如何查看僵尸进程:“z+”即僵尸进程
在这里插入图片描述

====================================================================================================================================================================================================================================
孤儿进程:父进程如果不等待子进程退出,在子进程之前就结束了自己的“生命”,此时子进程叫做孤儿进程

Linux为避免系统存在过多孤儿进程,init进程收留孤儿进程,变成孤儿进程的父进程

//运行以下代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
        int status;
        int i = 11;
        pid_t pid = fork();
        if(pid > 0)
        {
                        printf("this is father pid:%d\n",getpid());
        }
        else if(pid == 0)
        {
                while(1)
                {
                        printf("this is child pid:%d,father pid:%d\n",getpid(),getppid());
                        sleep(3);
                }
                exit(2);

        }
        return 0;
}
//结果如下:
this is father pid:6944
this is child pid:6945,father pid:6944
chm@ubuntu:~/linux$ this is child pid:6945,father pid:1722
this is child pid:6945,father pid:1722
this is child pid:6945,father pid:1722
...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值