信号 进程组

信号提供了一种机制,通知用户进程发生了这些异常 比如除数为0 ,那么内核就为他发送一个SIGLL信号

按下CURL+C 键 内核发送一个SIGINT 信号

一个发出没有接收的信号叫待处理信号、


进程组

1.每个进程属于一个进程组

2.一个子进程和它的父进程属于一个进程组

3.一个子进程和他的父进程属于一个进程组

获取进程组ID

#include <unistd.h>
#include <stdio.h>
int main(int argc, char **argv) {

    printf("%d",getpgrp());


    return 0;
}

信号处理问题

1.  待处理信号被阻塞

2. 待处理信号不会排队等待,任意类型最多只有一个待处理新哈

3. 系统调用可以被中断

4.不可以用信号来对其他进程中发生的事计数

#include <unistd.h>
#include <stdio.h>
#include <cstdlib>
#include <signal.h>
#include <wait.h>


void handler(int msg){
    pid_t  pid;
    if((pid=waitpid(-1,NULL,0))<0){
        printf("error");
        exit(0);
    }
    printf("handler child %d\n",pid);
    sleep(2);
    return;
}

int main(int argc, char **argv) {

    int i,n;
    char buf[1111];
    if((signal(SIGCHLD,handler))==SIG_ERR){
        printf("error");
        exit(0);
    }

    for(int i=0;i<3;++i){
        if(fork()==0){
            printf("hello from child %d \n",getpid());
            sleep(1);
            exit(0);
        }
    }

    if((n=read(STDIN_FILENO,buf,sizeof(buf)))<0){
        printf("read error \n");
        exit(0);
    }
    printf("Parent processing input \n");
    while(1){

    }




    return 0;
}


解决信号阻塞和不会排队等待的情况

#include <unistd.h>
#include <stdio.h>
#include <cstdlib>
#include <signal.h>
#include <wait.h>
#include <cerrno>


void handler(int msg){
    pid_t  pid;

    while((waitpid(-1,NULL,0))>0){
        printf("handler child %d\n",pid);
    }

    if(errno!=ECHILD)
    {
        printf("error");
        exit(0);
    }

    sleep(2);
    return;
}

int main(int argc, char **argv) {

    int i,n;
    char buf[1111];
    if((signal(SIGCHLD,handler))==SIG_ERR){
        printf("error");
        exit(0);
    }

    for(int i=0;i<3;++i){
        if(fork()==0){
            printf("hello from child %d \n",getpid());
            sleep(1);
            exit(0);
        }
    }

    if((n=read(STDIN_FILENO,buf,sizeof(buf)))<0){
        printf("read error \n");
        exit(0);
    }
    printf("Parent processing input \n");
    while(1){

    }




    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值