pthread_kill() 没有向主线程发送信号(主程序)

pthread_kill() not sending signal to main thread (main program)

信号可以在任何线程或主程序本身中接收。 我从主程序创建了一个辅助线程。所以我的程序中有两个线程 1. 主线程(进程本身) 2. 辅助线程。我只希望每当信号到达我的辅助线程时,它应该向我的主线程(程序)发送信号。我正在使用 pthread_kill(main_threadid, sig) 从辅助线程内的信号处理程序寄存器发送信号。但。我观察到每次发送到主线程的信号都收到了辅助子本身,并且信号处理程序陷入了接收发送信号的循环中。

#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>

// global variable
pthread_t main_threadId;
struct sigaction childpsa;

// Signal Handler for Auxiliary Thread  
void signalHandler_Child(int param)
{
    printf("Caught signal: %d in auxiliary Thread", param);
    pthread_kill(main_threadId, param);
}

void *childFun(void *arg)
{
    childpsa.sa_handler = signalHandler_Child;
    sigaction(SIGTERM, &childpsa, NULL);
    sigaction(SIGHUP, &childpsa, NULL);
    sigaction(SIGINT, &childpsa, NULL);
    sigaction(SIGCONT, &childpsa, NULL);
    sigaction(SIGTSTP, &childpsa, NULL);

    while (1) {
        // doSomething in while loop
    }
}

int main(void)
{
    main_threadId = pthread_self();

    fprintf(stderr, "pid to signal %d\n", getpid());

    // create a auxiliary thread here
    pthread_t child_threadId;
    int err = pthread_create(&child_threadId, NULL, &childFun, NULL);

    while (1) {
        // main program do something 
    }

    return 1;
}

假设我正在发送 SIGINT 以使用其进程 ID 从终端进行处理。

来自 Unix 环境中的高级编程:

Each thread has its own signal mask, but the signal disposition is shared by all threads in the process. This means that individual threads can block signals, but when a thread modifies the action associated with a given signal, all threads share the action. Thus, if one thread chooses to ignore a given signal, another thread can undo that choice by restoring the default disposition or installing a signal handler for the signal.

sigaction 调用正在为整个进程(以及该进程中的所有线程)设置信号处置。

当您向进程发送信号时,任何未阻塞该信号的线程(但只有 1 个线程)都可以接收它(尽管根据我有限的经验,通常首选主线程)。在您的代码中,主线程可能会收到信号,运行 信号处理程序,然后立即再次将信号发送给自己。

如果您希望您的单个辅助线程处理您进程的所有信号,您可以在主线程中使用 pthread_sigmask 来阻止相关信号:

sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGTERM);
sigaddset(&set, SIGHUP);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGCONT);
sigaddset(&set, SIGTSTP);
pthread_sigmask(SIG_BLOCK, &set, NULL);

这将确保信号不会传送到该线程。如果您在 pthread_create 之前执行此操作,则需要在您的辅助线程中解除对它们的阻塞。

然后您可以使用非信号线程间通信机制与主线程通信。