子进程的异步等待方式

一、子进程退出时会给父进程发送信号

    默认的父进程对子进程的操作是忽略,而子进程退出时会向父进程发送一个信号,我们现在要做的就是捕捉子进程退出时向父进程发送的信号。

代码如下:

  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <signal.h>
  4 #include <sys/wait.h>
  5 #include <stdlib.h>
  6 #include <sys/types.h>
  7
  8 void catchSig(int sig)
  9 {
 10         printf("get a sig : %d, pid : %d\n",sig, getpid());
 11 }
 12
 13 int main()
 14 {
 15         signal(SIGCHLD,catchSig);
 16         pid_t id = fork();
 17         if(id == 0)
 18         {
 19                 printf("I am child,quit!,pid = %d\n",getpid());
 20                 exit(1);
 21         }
 22         else
 23         {
 24                 waitpid(id, NULL, 0);
 25         }
 26         return 0;
 27 }


执行结果:

    由图,前一个pid为子进程当时的pid,后一个pid为父进程的pid,子进程发送信息并退出,父进程接受子进程发送的信号,并捕捉信号,显示出来。


二、父进程等待子进程的异步方式

    父进程自定义处理函数,采用非阻塞方式等待,当子进程退出时,向父进程发送信号,父进程进行回收,并反馈信息。

代码如下:

  1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include <signal.h>
  4 #include <sys/wait.h>
  5 #include <stdlib.h>
  6 #include <sys/types.h>
  7
  8 void catchSig(int sig)
  9 {
 10     do{
 11         pid_t ret = waitpid(-1, NULL, WNOHANG);
 12         if(ret > 0)
 13         {
 14                 printf("wait sucess: %d\n ",ret);
 15         }
 16         else
 17         {
 18                 printf("wait failed\n");
 19                 break;
 20         }
 21     }while(1);
 22 }
 23
 24 int main()
 25 {
 26         signal(SIGCHLD,catchSig);
 27         pid_t id = fork();
 28         if(id == 0)
 29         {
 30                 printf("I am child,quit!,pid = %d\n",getpid());
 31                 sleep(4);
 32                 exit(1);
 33         }
 34         else
 35         {
 36                 while(1)
 37                 {
 38                         printf("do father things!\n");
 39                         sleep(1);
 40                 }
 41         }
 42         return 0;
 43 }

执行结果:

    首先父进程做自己的工作,输出do things,接着子进程退出并发送信号,父进程接着做自己的事情,四秒之后,等待成功,但由于只执行一次,所以后一次等待失败,父进程依旧做自己的事情。到此程序结束,验证完成。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值