父进程等待子进程退出

父进程等待子进程退出==
1.wait()函数:

在这里插入图片描述
status参数:
是一个整型数指针
非空:
子进程退出状态放在它所指向的地址中。
空:
不关心退出状态
在这里插入图片描述
补充:wait和waitpid的区别:
waip使调用者阻塞,waitpid有一个选项,可以使调用者不阻塞,但是并没有什么使用意义,一般都是需要阻塞。
第一个参数:
在这里插入图片描述
第二个参数和wait一样
第三个参数:常用WNOHANG,不阻塞在这里插入图片描述

2.通过wait()收集的状态并不是准确的值需要通过以下宏解析:

在这里插入图片描述
如何查看僵尸进程:“z+”即僵尸进程
在这里插入图片描述

//代码如下:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
        int status;//将子进程退出的状态存储在status的地址
        int i = 4;
        pid_t pid = fork();//不是vfork
        if(pid > 0)
        {
                while(1)
                {
                        wait(&status);//父进程等待子进程退出
                        //waitpid的使用:waitpid(pid,&status,WNOHANG);但其实没有什么使用意义
                        if(WIFEXITED(status))printf("stutas = %d\n",WEXITSTATUS(status));//解析子进程退出返回的状态码
                        printf("this is father pid:%d\n",getpid());
                        sleep(3);
                }
        }
        else if(pid == 0)
        {
                while(--i)
                {
                        printf("this is child pid:%d\n",getpid());
                        sleep(3);
                }
                exit(2);
        }
        return 0;
}                                            

//运行结果:
this is child pid:6356
this is child pid:6356
this is child pid:6356
stutas = 2
this is father pid:6355
stutas = 2
this is father pid:6355
stutas = 2
this is father pid:6355
stutas = 2
this is father pid:6355
...
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值