如下程序,建立了一個子進程,且父進程等待子進程的退出而退出:spa
#include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main() { pid_t pid; char *message; int n; int exit_code; printf("fork program starting\n"); pid = fork(); switch(pid) { case -1: perror("fork failed"); exit(1); case 0: message = "This is the child"; n = 5; exit_code = 37; break; default: message = "This is the parent"; n = 3; exit_code = 0; break; } for(; n > 0; n--) { puts(message); sleep(1); } if(pid != 0) { int stat_val; pid_t child_pid; //while(1); //等待子進程的退出 child_pid = wait(&stat_val); printf("Child has finished: PID = %d\n", child_pid); if(WIFEXITED(stat_val)) printf("Child exited with code %d\n", WEXITSTATUS(stat_val)); else printf("Child terminated abnormally\n"); } exit(exit_code); }
運行結果:code
須要注意的是:假如上面程序中子進程退出了,可是父進程在wait()以前,子進程在進程表中的信息仍是存在的,可在wait()前面暫停,用#ps -al命令查看,結果以下:orm
此時,假如kill了父進程,那麼子進程就變成了「殭屍進程」(進程已經再也不運行,但它仍存在於系統下) ,此後子進程將認init進程爲父進程。由init進程接管,直到init進程發現並釋放它。blog