gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:06:39 24 4
gpt4 key购买 nike

信号可以在任何线程或主程序本身中接收。我从主程序创建了一个辅助线程。所以我的程序中有两个线程 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;
}

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

最佳答案

来自 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 之前执行此操作,则需要在辅助线程中解除对它们的阻塞。

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

关于linux - pthread_kill() 没有向主线程发送信号(主程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45413323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com