gpt4 book ai didi

c - 向 Linux 中的所有线程广播信号

转载 作者:可可西里 更新时间:2023-11-01 11:50:37 25 4
gpt4 key购买 nike

我想将信号从一个线程广播到进程中的所有其他线程。接收该信号的线程应该在信号处理程序中处理该信号。我怎样才能做到这一点?


我尝试了以下代码,但它通过打印用户定义的信号 1 退出。这是怎么回事?

#include  <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <pthread.h>

const int NTHREADS = 4;

long prev_fact, i;

void SIGhandler(int);

void SIGhandler(int sig)
{
printf("\nThread %lx Received a SIGUSR1.\n", pthread_self());
}

void* tfunc( void* arg )
{
printf( "Thread %lx executing...\n", pthread_self() );

while( 1 )
;
}

int main()
{
int i;
pthread_t t[NTHREADS];

for( i = 0; i < NTHREADS; i++ )
pthread_create( &t[i], NULL, tfunc, NULL );

for( i = 0; i < NTHREADS; i++ )
pthread_kill( t[i], SIGUSR1 );

for( i = 0; i < NTHREADS; ++i)
pthread_join(t[i], NULL);

return 0;
}

最佳答案

执行此操作的可移植 pthreads 方法是循环所有线程,为每个线程执行 pthread_kill()。这需要您维护代表进程中每个线程的所有 pthread_t 值的列表。

在 Linux 上,您可以读取 /proc/self/task 来确定当前进程中每个线程的 TID,然后使用 tgkill() 向它们发出信号(使用 getpid() 的结果作为 tgid 参数传递给 tgkill())。

请注意,glibc 不为 tgkill() 提供包装器 - 您必须使用 syscall() 调用它。

关于c - 向 Linux 中的所有线程广播信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6581297/

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