曲径通幽论坛

标题: 孤儿进程 [打印本页]

作者: beyes    时间: 2009-6-14 01:25
标题: 孤儿进程
如果一个子进程的父进程先于子进程结束,子进程就成为一个孤儿进程,它由 init 进程收养,成为 init  进程的子进程。下面程序说明:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
    pid_t pid;
   
    pid = fork();
    switch( pid ) {
        case 0:
          while(1) {
            printf("A background process, PID:%d
, ParentID: %d
",
                getpid(),getppid());
            sleep(3);
          }
        case -1:
            perror("Process creation failed
");
            exit(-1);
        default:
            printf("I am parent process, my pid is %d
", getpid());
            exit(0);
    }
    return 0;
}
       运行及输出
beyes@linux-beyes:~/C> ./fork3.exe
A background process, PID:15465
, ParentID: 15464
I am parent process, my pid is 15464
beyes@linux-beyes:~/C> A background process, PID:15465
, ParentID: 1
A background process, PID:15465
, ParentID: 1
A background process, PID:15465
, ParentID: 1
由第二行蓝色的提示符可以看到,父进程到这里已经退出。接下来子进程被 init 收养(parentID = 1)。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2