- 论坛徽章:
- 0
|
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
static pthread_t tid1, tid2;
static void *
thread_func( void * arg )
{
sigset_t tmask;
sigset_t twait;
int signum;
sigemptyset(&tmask);
sigemptyset(&twait);
sigaddset(&tmask,SIGTERM);
sigaddset(&twait,SIGTERM);
pthread_sigmask(SIG_BLOCK,&tmask,NULL);
printf("thread 2 already\n");
while(1){
sigwait(&twait,&signum);
printf("hi,in %d\n",signum);
}
return NULL;
}
static
void sig_term( int signum )
{
if(pthread_equal( tid1, pthread_self()))
printf("this thread one's sigterm process\n");
else if(pthread_equal( tid2, pthread_self()))
printf("this thread two's sigterm process\n");
else{
printf("wrong exit\n");
exit(1);
}
}
int
main()
{
sigset_t pmask;
sigset_t tmask;
tid1 = pthread_self();
if( signal( SIGTERM, sig_term ) == SIG_ERR ){
perror("SIGTERM register error");
exit(0);
}
sigfillset(&pmask);
sigemptyset(&tmask);
sigdelset(&pmask,SIGTERM);
sigaddset(&tmask,SIGTERM);
sigprocmask(SIG_SETMASK,&pmask,NULL);
// pthread_sigmask(SIG_BLOCK,&tmask,NULL);
if( pthread_create( &tid2, NULL, thread_func, NULL ) < 0 ){
perror("pthread create error");
exit(0);
}
printf("thread1 already\n");
while(1);
return 0;
}
想测试以下,发给两个线程所在的进程的sigterm信号会不会同时发给两个线程
这个是我kill PID的几次结果,都没有执行printf("hi,in %d\n",signum);
iant@giant-laptop:~/c/apue/test/thread_signal$ ./thread_signal
thread 2 already
thread1 already
this thread one's sigterm process
this thread one's sigterm process
this thread one's sigterm process
this thread one's sigterm process
this thread one's sigterm process
this thread one's sigterm process |
|