int main()
{
pid_t pid;
if( (pid = fork()) < 0)
exit(0);
else if(pid == 0) /* first child */
{
if( (pid = fork()) < 0)
exit(0);
else if(pid > 0)
{
//command;
exit(0);
}
exit(0);
}
if( (waitpid(pid,&stat,0)) != pid) /* wait for first child */
exit(0);
//command;
return 0;
{
pid_t pid;
if( (pid = fork()) < 0)
exit(0);
else if(pid == 0) /* first child */
{
if( (pid = fork()) < 0)
exit(0);
else if(pid > 0)
{
//command;
exit(0);
}
sleep(2);
printf("second child ,parent pid = %d\n", getppid() );
//command;exit(0);
}
if( (waitpid(pid,&stat,0)) != pid) /* wait for first child */
exit(0);
//command;
return 0;
}
在第二个子进程中用sleep以保证在打印父进程ID时第一个子进程已终止。如果不使第二个子进程睡眠,则在fork之后,它可能比其父进程先执行,于是它打印的父进程ID将是创建它的父进程,而不是Init进程(进程ID 1)。