#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int main()
{
pid_t pid;
//创建第一个子进程
pid = fork();
if (pid < 0){ // 出错
perror("fork error:");
exit(1);
}else if (pid == 0){//子进程
//子进程再创建子进程
printf("I am the first child process.pid:%d\tppid:%d\n",getpid(),getppid());
pid = fork();
if (pid < 0){
perror("fork error:");
exit(1);
}else if(pid == 0){ // 子进程
//睡眠3s保证下面的父进程退出,这样当前子进程的父亲就是 init 进程
sleep(3);
printf("I am the second child process.pid: %d\tppid:%d\n",getpid(),getppid());
exit(0);
}else if (pid >0){ //父进程退出
printf("first procee is exited.\n");
exit(0);
}
}else if(pid > 0){ // 父进程
// 父进程处理第一个子进程退出,回收其资源
if (waitpid(pid, NULL, 0) != pid){
perror("waitepid error:");
exit(1);
}
exit(0);
}
return 0;
}