标签:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<unistd.h> 4 int main() 5 { 6 pid_t pid,pr; 7 pid =fork(); 8 int status; 9 if(pid<0) 10 { 11 printf("Fork failed!\n"); 12 exit(1); 13 } 14 else if(pid==0) 15 { 16 printf("This child process with pid of %d.\n",getpid()); 17 exit(3); 18 } 19 else 20 { 21 do{ 22 pr=waitpid(pid,&status,WNOHANG);//如果子进程没有结束,那么父进程中的pr=0l;如果子进程结束,那么父进程中的pr值等于子进程的pid 23 if(pr==0) 24 { 25 printf("No child exited!\n"); 26 sleep(1); 27 } 28 }while(pr==0); 29 30 if(pr==pid) 31 { 32 33 if(WIFEXITED(status)) 34 { 35 printf("The child process success %d\n%d\n",pr,WEXITSTATUS(status)); 36 } 37 else 38 { 39 printf("ERROR!\n"); 40 } 41 } 42 else 43 { 44 printf("Error!\n"); 45 } 46 47 return 0; 48 } 49 50 }
程序运行结果:
1 No child exited! 2 This child process with pid of 7333. 3 The child process success 7333 4 3
标签:
原文地址:http://www.cnblogs.com/wireless-dragon/p/5180898.html