waitpid()函数的使用

#include <sys/types.h>
#incldue <sys/wait.h>
pid_t waitpid(pid_t pid,int *status,int options);

功能:回收指定进程号的子进程,可以设置是否阻塞。

参数:

        -pid:

                pid>0:某个子进程的pid;

                pid=0:回收当前进程组的所有子进程;

                pid=-1:回收所有的子进程,相当于wait();

                pid<-1:回收某个进程组的id的绝对值,回收指定进程的子进程。

        -options:设置阻塞或者非阻塞

                0:阻塞

                WNOHANG:非阻塞

        -返回值

                >0:返回子进程的id;

                =0:options=WNOHANG,表示还有子进程存在

                =-1:错误,或者没有子进程了

接下来我们进行操作,当options=WNOHANG时的程序和结果

  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <sys/stat.h>
  4 #include <unistd.h>
  5 #include <sys/wait.h>
  6 #include <stdlib.h>
  7 int main()
  8 {
  9         pid_t pid;
 10         for(int i=0;i<5;i++)
 11         {
 12                 pid=fork();
 13                 if(pid==0)
 14                 {
 15                         break;
 16                 }
 17         }
 18         if(pid>0)
 19         {
 20                 while(1)
 21                 {
 22                         sleep(1);
 23                         printf("parent:%d\n",getpid());
 24                         int st;
 25                         int ret=waitpid(-1,&st,WNOHANG);
 26                         if(ret==-1)
 27                         {
 28                                 break;//错误,没有子进程了
 29                         }
 30                         if(ret==0)
 31                         {
 32                                 continue;//还有子进程存在
 33                         }
 34                         if(ret>0)
 35                         {
 36                         if(WIFEXITED(st))
 37                         {
 38                                 printf("退出的状态码:%d\n",WEXITSTATUS(st));
 39                         }
 40                         if(WIFSIGNALED(st))
 41                         {
 42                                 printf("被那个信号给干掉了:%d\n",WTERMSIG(st));
 43                         }
 44                                 printf("child die,pid=%d\n",ret);
 45
 46                         }
 47                 }
 48         }
 49         else if(pid==0)
 50         {
 51                 while(1)
 52                 {
 53                 printf("child:%d\n",getpid());
 54                 sleep(1);
 55
 56                 }
 57         }
 58         return 0;
 59
 60 }

 此时我们会发现,waitpid()函数被父进程调用时一直是非阻塞状态,即每循环五个子进程就调用一次父进程。

如果我们把options=0,

 int ret=waitpid(-1,&st,0);

输出结果变成:

 只运行了一次父进程,剩下的都是子进程在运行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值