lv6 day13信号机制(上)学习笔记

 

忽略信号:对信号置之不理

捕捉信号:改变信号的行为

缺省方式:按信号的默认行为来做

 

     SIGCHLD        是子进程状态改变发给父进程的。

 

kill -l  查看所有的信号

kill -9 pid 无条件杀死一个进程

 

 

 

 

 

 

signal函数可以改变信号的默认行为。

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <linux/posix_types.h>

typedef void (*sighandler_t)(int);

sighandler_t oldact;

void handle(int sig){
    printf("I cath the SIGINT \n");
//    signal(SIGINT,oldact);//捕捉信号,执行oldact
}

int main(){

    oldact = signal(SIGINT,handle);//捕捉信号,执行handle

    while(1){

        sleep(1);
    }    


}

 

 

 struct sigaction结构体介绍

struct sigaction {
    void (*sa_handler)(int);
    void (*sa_sigaction)(int, siginfo_t *, void *);
    sigset_t sa_mask;
    int sa_flags;
    void (*sa_restorer)(void);
}

 

 使用信号捕捉实现了一个定时器功能。

功能:5秒钟后,每秒发送一次second timer信号。

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <linux/posix_types.h>
#include <sys/time.h>


typedef void (*sighandler_t)(int);

sighandler_t oldact;

void handle(int sig){
   if(sig == SIGINT){
        printf("I cath the SIGINT \n");
   }else if (sig==SIGALRM){
       printf("second timer \n");
   }
}


int main(){
    struct sigaction act;
    act.sa_handler = handle;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);//清空信号集
    struct itimerval timevalue;
    timevalue.it_interval.tv_sec = 1;//闹钟触发周期为1秒
    timevalue.it_interval.tv_usec = 0;
    timevalue.it_value.tv_sec = 5;//闹钟触发时间为5秒
    timevalue.it_value.tv_usec = 0;

    setitimer(ITIMER_REAL,&timevalue, NULL);
    sigaction(SIGALRM,&act,NULL);

    while(1){
    }

} 

 

 SIGCHLD信号配合wait函数来回收子进程:

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


void handle(int sig){

    wait(NULL);
    printf("Get sig =%d\n",sig);

}


int main(){
    pid_t pid;
    struct sigaction act;
    act.sa_handler = handle;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);

    pid = fork();

    if(pid>0){
        //wait(NULL);

        sigaction(SIGCHLD,&act,NULL);
        while(1){
            printf("this is father process\n");
            sleep(1);
        }

    }else if(pid==0){
        sleep(5);
        exit(0);
    }


}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值