信号之SIGCHLD

信号之SIGCHLD
SIGCHLD信号是子进程结束时发出来的信号,可用于在程序中捕获子进程结束的信号然后用wait函数将子进程资源回收。 优点:不会使父进程一直阻塞在wait函数处。

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

void signhander(int signo) {
        printf("grep pid:%d, signo:%d\n",getpid(), signo);
        wait(0);
        return;
}

int main(void)
{
        pid_t pid;
        if(signal(SIGCHLD, signhander) == SIG_ERR) {
                perror("signal error");
        }

        if ((pid = fork()) < 0) {
                perror("fork fail");
        } else if (pid > 0) { //父进程
                for(int i = 0; i<50; i++) {
                        printf("father pid: %d, %d.\n", getpid(), i);
                        sleep(1);
                }
        } else {//子进程
                for(int j = 0; j < 10; j++) {
                        printf("child pid: %d, %d.\n", getpid(), j);
                        sleep(1);
                }
        }

        return 0;
}

root@spark# ./chld_sig
father pid: 5918, 0.
child pid: 5919, 0.
father pid: 5918, 1.
child pid: 5919, 1.
father pid: 5918, 2.
child pid: 5919, 2.
father pid: 5918, 3.
child pid: 5919, 3.
father pid: 5918, 4.
child pid: 5919, 4.
father pid: 5918, 5.
child pid: 5919, 5.
father pid: 5918, 6.
child pid: 5919, 6.
father pid: 5918, 7.
child pid: 5919, 7.
father pid: 5918, 8.
child pid: 5919, 8.
father pid: 5918, 9.
child pid: 5919, 9.
father pid: 5918, 10.
grep pid:5918, signo:17
father pid: 5918, 11.
father pid: 5918, 12.
father pid: 5918, 13.
father pid: 5918, 14.
father pid: 5918, 15.
father pid: 5918, 16.
father pid: 5918, 17.
father pid: 5918, 18.
father pid: 5918, 19.
father pid: 5918, 20.
father pid: 5918, 21.
father pid: 5918, 22.
father pid: 5918, 23.
father pid: 5918, 24.
father pid: 5918, 25.
father pid: 5918, 26.
father pid: 5918, 27.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

spark'code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值