孤儿进程、僵尸进程

孤儿进程:父进程先于子进程结束,则子进程成为孤儿进程,子进程的父进程成为init进程,称为init进程领养孤儿进程。

/***
orphan.c
***/
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

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

    if (pid == 0) {
        while (1) {
            printf("I am child, my parent pid = %d
", getppid());
            sleep(1);
        }
    } else if (pid > 0) {
            printf("I am parent, my pid is = %d
", getpid());
            sleep(9);
            printf("------------parent going to die------------
");
    } else {
        perror("fork");
        return 1;
    }

    return 0;
}

僵尸进程:

进程终止,父进程尚未回收,子进程残留资源(PCB)存放于内核中,变为僵尸进程。

/***
zoom.c
***/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    pid_t pid, wpid;
    pid = fork();

    if (pid == 0) {
            printf("---child, my parent= %d, going to sleep 10s
", getppid());
            sleep(10);
            printf("-------------child die--------------
");
    } else if (pid > 0) {
        while (1) {
            printf("I am parent, pid = %d, myson = %d
", getpid(), pid);
            sleep(1);
        }
    } else {
        perror("fork");
        return 1;
    }

    return 0;
}
原文地址:https://www.cnblogs.com/wanghao-boke/p/11311820.html