C 在Linux中向所有线程广播信号

C 在Linux中向所有线程广播信号,c,linux,pthreads,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;

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



我尝试了以下代码,但它通过打印用户定义的信号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;
}
#包括
#包括
#包括
#包括
常数int=4;
很久以前的事实,我;
虚空信号发生器(int);
无效信号发生器(内部信号)
{
printf(“\n读取%lx收到一个SIGUSR1。\n”,pthread_self());
}
void*tfunc(void*arg)
{
printf(“线程%lx正在执行…\n”,pthread_self());
而(1)
;
}
int main()
{
int i;
pthread_t t[n线程];
对于(i=0;i
便携式pthreads实现这一点的方法是围绕所有线程循环,对每个线程执行
pthread\u kill()
。这需要您维护一个列表,其中包含表示进程中每个线程的所有
pthread\u t

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


请注意,glibc没有为
tgkill()
提供包装器-您必须使用
syscall()

调用它,下面的代码现在可以工作了

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

const int NTHREADS = 4;

void  SIGhandler(int);     

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

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

  while( 1 )
    ;
}

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

  signal(SIGUSR1, SIGhandler);

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

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

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

  return 0;
}
#包括
#包括
#包括
#包括
常数int=4;
虚空信号发生器(int);
无效信号发生器(内部信号)
{
printf(“\n读取%lx收到一个SIGUSR1。\n”,pthread_self());
}
void*tfunc(void*arg)
{
printf(“线程%d(%lx)正在执行…\n”,*((unsigned int*)arg),pthread_self());
而(1)
;
}
int main()
{
int i;
国际贸易总指数[NTHREADS];
pthread_t t[n线程];
信号(SIGUSR1、SIGhandler);
对于(i=0;i
我尝试了以下代码,但它通过打印用户定义的信号1退出。发生什么事?void SIGhandler(int sig){printf(“\n线程%lx收到一个SIGUSR1.\n”,pthread_self())}void*tfunc(void*arg){printf(“线程%lx执行…\n”,pthread_self());而(1)}int main(){int i;pthread_t[NTHREADS];for(i=0;isigaction()注册您的信号处理函数。您只需执行一次,因为信号处理在所有线程之间共享。请注意,按照您编写的方式,它不会向主线程本身发送信号(在主线程中使用
pthread\u self()
,以获取其线程句柄)。