我不知道爲什麼這個程序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),它也回答了爲什麼要避免。 –