Ayuto

Linux catch hardware exception

Jul 14th, 2016
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include <signal.h>
  2. #include <setjmp.h>
  3.  
  4. jmp_buf env;
  5. void (*prev_handler)(int);
  6.  
  7. void segv_handler(int signal)
  8. {
  9.     longjmp(env, 1);
  10. }
  11.  
  12. /*
  13. Macros to temporarily catch a segmentation fault.
  14.  
  15. Usage:
  16.  
  17. SEGV_TRY()
  18.     // Risky code...
  19. SEGV_CATCH()
  20.     // Error handling...
  21. SEGV_END()
  22.  
  23. // Other code...
  24. */
  25. #define SEGV_TRY() \
  26.     prev_handler = signal(SIGSEGV, segv_handler); \
  27.     if (setjmp(env) == 0) {
  28.  
  29. // The previous signal handler should be restored as soon as possible.
  30. // That's why it gets restored either at the end of the try block
  31. // (successful execution) or at the beginning of the catch block
  32. // (erroneous execution).
  33. #define SEGV_CATCH() \
  34.         signal(SIGSEGV, prev_handler); \
  35.     } else { \
  36.         signal(SIGSEGV, prev_handler);
  37.  
  38. #define SEGV_END() \
  39.     }
  40.  
  41. /*
  42. Macro to replace SEGV_CATCH() and SEGV_END(). A RuntimeError will be raised
  43. in the error handling code.
  44.  
  45. Usage:
  46.  
  47. SEGV_TRY()
  48.     // Risky code...
  49. BOOST_SEGV_CATCH()
  50.  
  51. // Other code...
  52. */
  53. #define BOOST_SEGV_CATCH() \
  54.     SEGV_CATCH() \
  55.         BOOST_RAISE_EXCEPTION(PyExc_RuntimeError, "Segmentation fault.") \
  56.     SEGV_END()
Advertisement
Add Comment
Please, Sign In to add comment