Avoid zombie processes by calling fork twice
/* * Avoid zombie processes by calling fork twice. * APUE-2e 程序清单8-5 */ #include <unistd.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include "sig_wait_proc.h" int main() { pid_t pid; if( (pid = fork()) < 0 ) { printf("fork error.\n"); exit(0); } else if(pid == 0) /* first child */ { init_wait(); if( (pid = fork()) < 0 ) { printf("fork error.\n"); exit(0); } else if(pid > 0) { tell_proc(pid); /* tell child on exiting */ exit(0); } /* We're the second child; our parent becomes init as soon as our real parent exits. */ wait_proc(); /* wait for parent */ printf("second child, parent pid = %d\n", getppid()); exit(0); } if(waitpid(pid, NULL, 0) != pid) /* wait for first child */ { printf("waitpid error.\n"); exit(1); } printf("parent, first child pid = %d\n", pid); exit(0); }
说明:
init_wait(),tell_proc(),wait_proc()见http://blog.csdn.net/duyiwuer2009/article/details/7948026