c - 是否可以同时使用自定义 sigaction 信号处理程序和 pthread_sigmask?

标签 c linux posix signals

我正在实现一个简单的计时器,它会在到期时抛出一个 RT 信号。我想要做的是注册一个信号处理程序(使用 sigaction),它在信号发生时被调用。同时,主代码等待直到使用 sigwaitinfo 调用信号。

单独实现信号处理程序或 sigwaitinfo 都可以正常工作。但是,当两者都使用时,永远不会调用信号处理程序。我试着调换顺序;即在阻止信号之前注册处理程序。没有区别。

这是代码

// gcc -Wall -o sigwait_example sigwait_example.c -lrt
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#include <string.h>

#define install_handler(sig,sa) if( sigaction(sig, &sa, NULL) == -1 ){ \
                                    perror("sigaction"); }
#define SIG SIGRTMIN+1

volatile int flag=0;

void handler(int signum){
    flag++;
}

int main(void){
    struct itimerspec its;
    sigset_t blocked;
    siginfo_t si;
    timer_t timerid;
    struct sigevent evt;
    struct sigaction sa;

    evt.sigev_notify = SIGEV_SIGNAL;
    evt.sigev_signo = SIG;
    evt.sigev_value.sival_ptr = &timerid;
    if ( timer_create(CLOCK_REALTIME, &evt, &timerid) ){
        perror("timer_create");
    }

    //setup timer
    its.it_value.tv_sec = 0;
    its.it_value.tv_nsec = 0.1*1E9;
    its.it_interval.tv_sec = 0;
    its.it_interval.tv_nsec = 0;

    //arm the timer 
    if ( timer_settime(timerid, 0, &its, NULL) )
        perror("timer_settime");

    sigemptyset(&blocked);
    sigaddset(&blocked, SIG);
    //add SIG to blocked signals
    pthread_sigmask(SIG_BLOCK, &blocked, NULL);

    sa.sa_flags = SA_SIGINFO; //use this flag to set custom handler
    sa.sa_sigaction = handler;
    sigemptyset(&sa.sa_mask);
    install_handler(SIG,sa);

    while ( sigwaitinfo(&blocked, &si) == -1 && errno == EINTR );
    printf("received signal: %s, flag=%d\n",strsignal(si.si_signo),flag);       
    //while(flag==0) sleep(1); //use this when only signal handler is used

    timer_delete(timerid);

    return 0;
}

我这样做主要是出于教育目的,因为我需要尽可能多地了解如何发送/阻止线程,因为我将在线程中使用它们。

最佳答案

这是不可能的,因为 sigwaitinfo() 从队列中删除了信号。

但是,您可以使用 sigaction(SIG, NULL, &sa) 检索此信号的 sigaction 结构并执行处理程序。

关于c - 是否可以同时使用自定义 sigaction 信号处理程序和 pthread_sigmask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7207289/

相关文章:

c - 使用 ARM gcc 时,LD 给出奇怪的错误并且找不到现有文件

c - Linux shell 不执行我的 c 程序

linux - 如何检查 gz 文件是否未正确完成写入

c++ - 使来自线程的数据流对所有其他线程可读

bash - POSIX 是否定义了向终端发送 NUL 时的行为?

c - 如果我没有流但有文件描述符,如何使用 fgets 或 getline?

c - 为结构体数组分配内存时出现错误

c - 链表维护根指针地址,以便在构建后读取它

linux - 将 WiFi Dongle 与 Beaglebone Black-Issue 集成

linux命令行使用提供的参数重命名所有文件