多进程——waitpid()函数的小例子

本例中使用fork()创建一个子进程,然后让子进程暂停5s,接下来对原有的父进程使用waitpid()函数,利用WNOHANG使父进程不会阻塞每隔一秒判断子进程是否退出。

 1 #include"my.h"
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 int main(){
 5     pid_t pid,ret;
 6     if((pid=fork())<0){
 7 
 8         perror("fork ERROR!");
 9         return 1;
10     }else if(pid==0){
11 
12         printf("%d:进程在运行
",getpid());
13         sleep(10);
14         exit(0);
15     }else if(pid>0){
16 
17         do{
18 
19             ret=waitpid(pid,NULL,WNOHANG);
20             if(ret==0){
21 
22                 printf("the child prociess has no exited
");
23                 sleep(1);
24             }
25         }while(ret==0);
26 
27         if(pid==ret){
28         
29             printf("child process exit
");
30         }
31     }
32 
33 
34     return 0;
35 }

原文地址:https://www.cnblogs.com/lanbofei/p/9574305.html