我不知道为什么这个程序crashs当报警处理共完成其工作,由于malloc的声明(LINE-1),虽然它从未被称为的malloc分段故障时,报警处理程序共完成
当我评论LINE1 LINE2 OR代码继续没有任何问题,但评论LINE3当程序仍然crashs
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void handler (int sig) {
printf ("Hi I'm at handler\n");
}
int main() {
int *pm, f = 0;
struct sigaction sa;
sa.sa_handler = &handler;
sigaction (SIGALRM, &sa, NULL);
alarm (2); // LINE1
while (1) {
if (f == 1) {
pm = (int *) malloc (sizeof (int)); // LINE2
if (pm)
printf ("memory allocated at loop\n");
}
else {
printf ("Wait\n");
usleep (200000); // LINE3
}
}
return 0;
}
结果:
Wait
Wait
Wait
Wait
Wait
Wait
Wait
Wait
Wait
Wait
Hi I'm at handler
Segmentation fault (core dumped)
注:
这个问题面临的我,可以让我写了这个程序,以显示它 我工作在Ubuntu下,并用gcc编译不能在这里发表较大的应用程序
在信号处理程序中使用printf(和任何'睡眠'功能)不是一个好主意 –
阅读[如何避免在信号处理程序中使用printf?](http://stackoverflow.com/questions/16891019/how -to-avoid-using-printf-in-a-signal-handler),它也回答了为什么要避免。 –