catch_child.cpp

/*
 * function: 父进程使用sigaction()函数捕捉SIGCHLD信号子进程
 *
 * 2020-12-27
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>

void func(int signo)
{
    pid_t wpid;
    int status;

    while ((wpid = waitpid(-1, &status, 0)) != -1)         // 阻塞回收, -1表示没有子进程
    {
        if (WIFEXITED(status))
        {
            printf("catch a child %d, normal exit status:%d\n", wpid,  WEXITSTATUS(status));
        }
        else if (WIFSIGNALED(status))
        {
            printf("catch a child %d, kill by signal:%d\n", wpid, WTERMSIG(status));
        }
        else if (WCOREDUMP(status))
        {
            printf("catch a child %d, stop status:%d\n", wpid, WIFSTOPPED(status));
        }
    }
}

int main(int argc, char *argv[])
{
    pid_t pid = 0;

    // 阻塞SIGCHLD信号,防止在父进程注册捕捉函数之前子进程退出
    sigset_t set;
    sigemptyset(&set);
    sigaddset(&set, SIGCHLD);
    sigprocmask(SIG_BLOCK, &set, NULL);

    int ii = 0;
    for (ii = 0; ii < 5; ++ii)
    {
        pid = fork();
        if (0 == pid)
        {
            break;      // 子进程跳出循环
        }
        else if (-1 == pid)
        {
            perror("fork failed");
            exit(1);
        }
    }

    if (pid > 0)    // 父进程
    {
        printf("I'm parent:%d\n", getpid());

        struct sigaction act;
        act.sa_handler = func;       // 设置回调函数
        sigemptyset(&act.sa_mask);  // 清空sa_mask
        act.sa_flags = 0;           // 设置默认属性

        sigaction(SIGCHLD, &act, NULL);     // 注册信号捕捉

        // 解除阻塞
        sigprocmask(SIG_UNBLOCK, &set, NULL);

        while(1);       // 模拟父进程后续操作
    }
    else if (0 == pid)   // 子进程
    {
        printf("I'm a child:%d\n", getpid());
        return ii;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值