child的宿命

previous on process:

linux进程创建可以使用fork和vfork

进程在创建后有三种命运:

destiny one:正常情况

此时子进程先于父进程死亡,父进程调用wait或者wait_pid为其收尸。

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/unistd.h>

extern int errno;

int main()
{
    pid_t pid;

    if((pid = fork()) < 0)
    {
        printf("fork return error %s\n", strerror(errno));
        exit(-1);
    }
    else if(pid == 0)
    {
        printf("child process is deading!\n");
        exit(0);
    }

    if(wait(0) != pid)
    {
        printf("wait error %s\n", strerror(errno));
    }
    system("ps -o pid,ppid,stat,command");

    printf("parent process is going dead!\n");

    exit(0);
}

destiny two:成为僵尸进程

在子进程介绍后父进程没有为其收尸

include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
extern int errno;

int main()
{
    pid_t pid;
    pid = fork();

    if(pid < 0)
    {
        printf("fork return error %s\n", strerror(errno));
        exit(-1);
    }
    else if(pid == 0)
    {
        printf("this could be a zombie process!\n");
        _exit(0);
    }
    else
    {
        system("ps -o pid,ppid,stat,command");
        printf("parent process dead!\n");
    }
    exit(0);
}

如果父进程是守护进程则需要对这种情况进行处理,zombie会占用系统一定的资源,当zombie进程过多后会照成系统性能下降,不是daemon程序倒是无所谓,因为还有init进程可以收拾它

destiny three:被init收监

在子进程退出之前父进程就结束了运行,那么这个时候init会成为该子进程的父进程

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>

extern int errno;
int main()
{
    pid_t pid;
    pid = fork();
    if(pid < 0)
    {
        printf("fork return error %s\n", strerror(errno));
        exit(-1);
    }
    else if(pid == 0)
    {
        sleep(1);
        printf("make sure parent is dead\n");
        _exit(0);
    }
    else
    {
        system("ps -o pid,ppid,stat,command");
        printf("parent is go away!\n");
    }
    exit(0);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值