C语言 等待子进程结束 waitpid函数

        当用fork函数创建一个新的子进程的时候,子进程就有了新的生命周期,并将在其自己的地址空间内独立运行。如果我们需要在子进程结束时去做一些处理,可以使用waitpid函数等待子进程结束

pid_t waitpid(pid_t __pid, int *__stat_loc, int __options)

第一个参数__pid为需要等待的进程号,第二个参数为子进程的状态信息,第三个参数为另外的选项,如果不想使用,可以设为0

状态信息:等待子进程结束时把子进程的状态传给status

在这里补充介绍四组宏:

1、WIFEXITED(status): 若此值为非0,表明进程正常结束,此时可通过WEXITSTATUS(status)获取进程退出状态(exit时参数)

2、WIFSIGNALED(status):若此值为非0,表明进程异常终止(被信号中断),此时可通过WTERMSIG(status)获取使得进程退出的信号编号

3、 WIFSTOPPED(status):若此值为非0,表明进程处于暂停状态,此时可通过WSTOPSIG(status)获取使得进程暂停的信号编号

4、 WIFCONTINUED(status) 非0表示进程暂停后已经继续运行

示例代码:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
    pid_t Child_pid;

    Child_pid=fork();//创建子进程


    if(Child_pid==0)
    {
        for(int i=0;i<3;i++)
        {
            printf("This is a child process!num:%d\n",i);
            sleep(2);
        }
        printf("Child process pid:%d\n",getpid());
        printf("parent process pid:%d\n",getppid());
        exit(3); //以状态3退出
    }
    else if(Child_pid<0) //fork返回值为0代表子进程创建失败
    {
        printf("create child process error!\n");
    }
    else
    {
        int status=0;
        printf("this is parent process!\n");
        
        waitpid(Child_pid,&status,0);   //子进程结束时将子进程状态传给status


        if(WIFEXITED(status))  //如果子进程正常退出
        {
            printf("child exit with %d\n", WEXITSTATUS(status));//输出子进程的退出状态
        }
        printf("Parent process pid:%d\n",getpid());
        printf("parent's parent process pid:%d\n",getppid());
    }

    return 0;
}

运行结果:

this is parent process!
This is a child process!num:0
This is a child process!num:1
This is a child process!num:2
Child process pid:6218
parent process pid:6217
child exit with 3
Parent process pid:6217
parent's parent process pid:2939

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值