我要趕SIGBUS,我的代碼如下所示:捕捉SIGBUS和C++
#include <stdlib.h>
#include <signal.h>
#include <iostream>
#include <stdio.h>
void catch_sigbus (int sig)
{
//std::cout << "SIGBUS" << std::endl;
printf("SIGBUS\n");
exit(-1);
}
int main(int argc, char **argv) {
signal (SIGBUS, catch_sigbus);
int *iptr;
char *cptr;
#if defined(__GNUC__)
# if defined(__i386__)
/* Enable Alignment Checking on x86 */
__asm__("pushf\norl $0x40000,(%esp)\npopf");
# elif defined(__x86_64__)
/* Enable Alignment Checking on x86_64 */
__asm__("pushf\norl $0x40000,(%rsp)\npopf");
# endif
#endif
/* malloc() always provides aligned memory */
cptr = (char*)malloc(sizeof(int) + 1);
/* Increment the pointer by one, making it misaligned */
iptr = (int *) ++cptr;
/* Dereference it as an int pointer, causing an unaligned access */
*iptr = 42;
return 0;
}
當我用printf,它可以通過調用catch_sigbus趕上,但是當我使用COUT,它不能。那麼任何人都可以幫助我?我在Ubuntu 12.04上運行。
我還有一個問題。當我捕捉到SIGBUS時,我如何獲得si_code? BUS_ADRALN/BUS_ADRERR/BUS_OBJERR
看到這個:http://stackoverflow.com/questions/12139609 /爲什麼不輸出控制檯上的信號處理 –
您不能從信號處理程序調用'printf',也不能使用信號處理程序中的'cout'。如果一個函數使用'printf'或'cout'被一個信號中斷?另外,[你不能從信號處理程序調用'exit'](http://bytes.com/topic/c/answers/440109-signal-handler-sigsegv)。 –
我測試了它,並且與printf一起工作 – thanhtv