fork()函数的返回值是返回两次的,在父进程中返回子进程的pid,在子进程中返回0。借此我们可以在代码中区分开父子进程运行的代码。
进入函数后首先fork(),产生一个子进程,在子进程的进程空间的环境创建好之前,父进程就已经运行完并打印了b和c,然后子进程打印a和c。
2. 子死父清场(life_period.c)
#include#include#include#includeintmain(void){
pid_t pid,wait_pid;int status;
pid =fork();if(pid==-1){perror("Cannot create new process");exit(1);}elseif(pid==0){printf("child process id: %ld
",(long)getpid());pause();_exit(0);}else{#if 1 /* define 1 to make child process always a zomie */printf("ppid:%d
",getpid());while(1);#endifdo{
wait_pid=waitpid(pid,&status, WUNTRACED | WCONTINUED);if(wait_pid ==-1){perror("cannot using waitpid function");exit(1);}if(WIFEXITED(status))printf("child process exites, status=%d
",WEXITSTATUS(status));if(WIFSIGNALED(status))printf("child process is killed by signal %d
",WTERMSIG(status));if(WIFSTOPPED(status))printf("child process is stopped by signal %d
",WSTOPSIG(status));if(WIFCONTINUED(status))printf("child process resume running....
");}while(!WIFEXITED(status)&&!WIFSIGNALED(status));exit(0);}}