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

标签 c linux pthreads

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


我尝试了以下代码,但它通过打印用户定义的信号 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/

相关文章:

c - 为什么 printf 在多线程程序中不起作用?

c 内存分配

c - strcpy() 跳过数组元素

java - 如何在 Windows 中使用 JNA 截屏?

linux - 在没有 Internet 访问权限且没有 root 的情况下部署 linux 二进制文件?

c++ - Quest 库(Quest 身份验证服务)线程安全吗?

c - 无法理解 C 中函数的指针

c - 如何在Linux中添加延迟而不放弃CPU周期

c++ - 关于学习 Xlib ("the Linux Petzold"的书籍/资源?)

c++ - 如何在 Linux 上的 C++ (pthread) 多线程程序中查找(段错误)错误?