【发布时间】:2011-09-16 06:11:49
【问题描述】:
下面的程序为整个进程设置 SIG_ALRM 处理程序,创建一个线程,向新创建的线程发送 SIG_ALRM 信号。 在 SIG_ALRM 处理程序中调用 pthread_exit。 结果 - 分段错误。 如果你在发送信号之前睡觉 - 好的。
看起来在 pthread_exit 的那一刻新线程还没有启动。 我尝试使用 gdb 定位分段错误,但无法使用 gdb 重现崩溃。
什么导致分段错误?
谢谢!
#include <signal.h>
#include <pthread.h>
#include <iostream>
#include <cassert>
using namespace std;
void* threadFunc(void* arg) {
cout << "thread: started. sleeping..: " << pthread_self() << endl;
sleep(10);
cout << "thread: exit" << endl;
return NULL;
}
void alrm_handler(int signo) {
cout << "alrm_handler: " << pthread_self() << endl;
pthread_exit(NULL); //if comment - no segmentation fault
}
int main() {
cout << "main: " << pthread_self() << endl;
struct sigaction act;
act.sa_handler = alrm_handler;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGALRM, &act, NULL);
pthread_t t;
int rc = pthread_create(&t, NULL, threadFunc, NULL);
assert(rc == 0);
// usleep(1000); //if Uncomment - no segmentation fault
rc = pthread_kill(t, SIGALRM);
assert(rc == 0);
pthread_join(t, NULL);
cout << "main: exit" << endl;
return 0;
}
输出:
主:140130531731232
alrm_handler: 140130504095488
分段错误
【问题讨论】:
标签: linux pthreads segmentation-fault signals