模拟实现僵尸进程和孤儿进程

僵尸进程:

如果子进程退出时,没有给父进程反馈信息(1.结果正确退出  2.结果不正确退出  3.程序异常终止),且父进程没有回收,可能造成“僵尸进程”,进而引发内存泄漏。

#include
#include
#include
#include


int main()
{
    pid_t id = fork();
    if(id == 0)
    {
        //child
        printf("child pid = %d",getpid());
        exit(1);
    }
    else if(id > 0)
    {
        //father
        while(1)
        {
        printf("father pid = %d\n",getpid());
        sleep(2);
        }
    }
    else
    {
        perror("fork");
    }
    
    return 0;
}

father pid = 7079
child pid = 7080
root       7079  0.0  0.0   4168   344 pts/0    S+   16:52   0:00 
root       7080  0.0  0.0      0     0 pts/0    Z+   16:52   0:00
孤儿进程:

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

#include
#include
#include
#include


int main()
{
    int id = fork();
    if(id == 0)
    {
        //child
        while(1)
        {
            printf("child pid = %d  father ppid = %d\n",getpid(),getppid());
            sleep(5);
        }
    }
    else if(id > 0)
    {
        //father
        printf("child pid = %d  father pid = %d\n",getpid(),getppid());
        exit(1);
        
    }
    else
    {
        perror("fork");
    }
    
    return 0;
}
child pid = 8034  father ppid = 1

因为父进程退出,子进程的被1号进程收养,故father ppid 是1   也就是它的父进程变成了1号,子进程的pid 不变。

你可能感兴趣的:(Linux)