环境:Vmware Workstation;CentOS-6.4-x86_64
孤儿进程:
1、父进程消失,子进程仍然存在,那么这个子进程就是孤儿进程。
2、孤儿进程的PPID是1,此时子进程的父进程变成init()。
程序:
使用程序,实现一个孤儿进程,并得到孤儿进程的PPID。
程序如下main.c:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *args[])
{
// 执行fork并获取返回值
pid_t id = fork();
// 判断fork是否成功
// 当返回值为-1时,说明fork失败
if (id == -1)
{
printf("fork failed : %s", strerror(errno));
}
if (id > 0)
{
// 父进程立即退出
exit(0);
}
else
{
// 子进程休眠3秒,确保父进程已经退出,再继续执行
sleep(3);
// 获取PPID并打印输出
printf("PPID : %d\n", getppid());
}
return 0;
}
编译并执行程序: [negivup@negivup mycode]$ gcc -o main main.c
[negivup@negivup mycode]$ ./main
[negivup@negivup mycode]$ PPID : 1
从程序的执行结果中可以看出,孤儿进程的父进程的PID是1。
PS:根据传智播客视频学习整理得出。