代码操作步骤如下:
[tqg@localhost test]$ vi test.cpp
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void signal_handler(int sig)
{
printf("catch signal: %d,thread id = %u\n",sig,pthread_self());
pthread_exit(0);
}
void* thread_handler(void*arg)
{
signal(SIGQUIT,signal_handler);
printf("thread arg = %s\n",(char*)arg);
sleep(10);
printf("in thread\n");
return (void*)0;
}
int main()
{
char* pArg = "hello";
pthread_t tid;
pthread_create(&tid,NULL,thread_handler,pArg);
printf("main thread id = %u\n",pthread_self());
sleep(2);
printf("killing now\n");
pthread_kill(tid,SIGQUIT);
sleep(20);
printf("exit main now\n");
return 0;
}
~
~
~
~
"test.cpp" 42L, 648C written
[tqg@localhost test]$ g++ -o test test.cpp -lpthread
[tqg@localhost test]$ ./test
main thread id = 3086875296
thread arg = hello
killing now
catch signal: 3,thread id = 3086871472
exit main now
[tqg@localhost test]$
可以看出,信号处理函数的执行是在要捕获信号的子线程thread_handler的上下文中执行的。