A collection of basic/generally desirable code I use across multiple C++ projects.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
1.6 KiB

1 year ago
  1. #ifndef SIGNAL_HANDLER_H
  2. #define SIGNAL_HANDLER_H
  3. #include <signal.h> // for signal() and the SIG macros
  4. #include "types.h"
  5. #include "print.h"
  6. // the running process can receive and respond to a variety of platform-dependent 'signals' during runtime from the OS.
  7. // freebsd has something like 30 signals, windows has a subset, just 6. we'll just deal with 6.
  8. static inline void defaultHandler(s32 signal) {
  9. TYPES_H_FTAG;
  10. switch (signal) {
  11. case SIGSEGV:
  12. case SIGABRT:
  13. print("%serror%s: %d\n", ANSI_RED, ANSI_RESET, signal);
  14. trace();
  15. case SIGINT:
  16. die("Bye! (SIGINT)\n");
  17. case SIGTERM:
  18. die(" We were asked to stop (SIGTERM).\n");
  19. case SIGFPE:
  20. die(" (SIGFPE).\n");
  21. case SIGILL:
  22. die(" (SIGILL).\n");
  23. default:
  24. die(" unknown/non-standard signal raised: %d\n", signal);
  25. break;
  26. }
  27. }
  28. static void setSignalHandlers(void(*handler)(s32 signal) = defaultHandler) {
  29. TYPES_H_FTAG;
  30. if (signal(SIGSEGV, handler) == SIG_ERR) die("failed to set SIGSEGV handler... zzz...\n");
  31. if (signal(SIGABRT, handler) == SIG_ERR) die("failed to set SIGABRT handler... zzz...\n");
  32. if (signal(SIGFPE, handler) == SIG_ERR) die("failed to set SIGFPE handler... zzz...\n");
  33. if (signal(SIGILL, handler) == SIG_ERR) die("failed to set SIGILL handler... zzz...\n"); // does this fire on using sprintf (on Catalina)?
  34. if (signal(SIGINT, handler) == SIG_ERR) die("failed to set SIGINT handler... zzz...\n");
  35. if (signal(SIGTERM, handler) == SIG_ERR) die("failed to set SIGTERM handler... zzz...\n");
  36. }
  37. #endif