2

它是一个示例程序,用于检查 sigprocmask 是否真的阻塞了与我的计时器相关的 SIGALRM 信号。事实证明不是。即使信号被阻塞,我的处理程序也会被调用。如果有人能指出为什么会这样,我将不胜感激。这是代码:

#include <signal.h> 
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

timer_t timer_ID;
static void timer_handler(int signo, siginfo_t *sig_info, void *sig_ucontext){  
    if(sig_info->si_value.sival_ptr != &timer_ID){
        printf("This signal is stray and didnt come from the timer we setup. Exiting the program!\n");
        exit(1);
     }
     else{
        printf("Caught signal %d from timer\n", signo);
     }
     return;
}//func end

void main(void)
{   
    struct sigevent sev;         // for creating the timer  
    sigset_t sigmask;   
    struct sigaction sa = {0};          
    struct itimerspec its;  
    its.it_interval.tv_sec = 0;
    its.it_interval.tv_nsec = 500000; 

    its.it_value.tv_sec = its.it_interval.tv_sec;
    its.it_value.tv_nsec = its.it_interval.tv_nsec;

    sa.sa_flags = SA_SIGINFO | SA_RESTART; 
    sa.sa_sigaction = timer_handler;

    if (sigaction(SIGALRM, &sa, NULL) == -1){
       fprintf(stderr, "sigaction register error\n");
       exit(1);
    }   
    //BLOCK SIG
    sigemptyset (&sigmask);
    sigaddset (&sigmask, SIGALRM);
    if (sigprocmask(SIG_BLOCK, &sigmask, NULL) == -1) {
        fprintf (stderr, "Failed to set signal mask!\n");
        exit (1);
    }   

    //CREATE TIMER
    sev.sigev_signo = SIGALRM; 
    sev.sigev_notify = SIGEV_SIGNAL; 
    sev.sigev_value.sival_ptr = &timer_ID; 

    if(timer_create(CLOCK_MONOTONIC, &sev, &timer_ID) != 0){ 
        printf("Create timer error!\n");        
        exit (1);
    } 
    // START TIMER
    if(timer_settime(timer_ID, 0, &its, NULL) !=0){
        printf("ERROR setting the timer!!!!\n");
        exit(1);
    }

    while(1);  //signal is blocked so should never go to handler
}//main end
4

0 回答 0