- /*
- * rov_posixsignal2c++exception001.cpp - test whether a POSIX signal can be
- * turned into a C++ exception
- *
- * Compile with $ g++ -std=c++17 -g -Wall -Wextra rov_posixsignal2c++exception001.cpp #
- *
- * Written by Roland Mainz <roland.mainz@rovema.de>
- */
- #include <cstdio>
- #include <csignal>
- #include <exception>
- #include <string>
- #include <cstring>
- #include <stdexcept>
- class posix_signal_exception : public std::exception {
- private:
- int sig_num;
- std::string msg;
- public:
- explicit posix_signal_exception(int signum) : sig_num(signum) {
- /* FIXME: We should store the whole siginfo() data here */
- msg = "Caught POSIX signal: " + std::to_string(signum) +
- " (" + strsignal(signum) + ")";
- }
- /*[[nodiscard]]*/ const char* what() const noexcept override {
- return msg.c_str();
- }
- /*[[nodiscard]]*/ int signum() const noexcept {
- return sig_num;
- }
- };
- extern "C"
- void signal_handler(int signum) {
- throw posix_signal_exception(signum);
- }
- void setup_signal_handler(int signum) {
- struct sigaction sa;
- (void)memset(&sa, 0, sizeof(sa));
- sa.sa_handler = signal_handler;
- (void)sigemptyset(&sa.sa_mask);
- sa.sa_flags = SA_NODEFER;
- if (sigaction(signum, &sa, NULL) == -1) {
- throw std::runtime_error("setup_signal_handler: Failed to setup signal handler.");
- }
- }
- int main(int ac, char *av[])
- {
- (void)ac;
- (void)av;
- try {
- setup_signal_handler(SIGFPE);
- (void)fprintf(stderr, "Signal handler installed. Triggering a divide-by-zero...\n");
- volatile int zero = 0;
- int result = 10 / zero;
- (void)fprintf(stderr, "Result: %d\n", result);
- } catch (const posix_signal_exception &e) {
- (void)fprintf(stderr, "#### posix_signal_exception caught\n");
- (void)fprintf(stderr, "Message: '%s'\n", e.what());
- (void)fprintf(stderr, "Signal Number: %d\n", e.signum());
- } catch (const std::exception& e) {
- (void)fprintf(stderr, "#### Standard exception caught: '%s'\n", e.what());
- }
- return EXIT_SUCCESS;
- }
rov_posixsignal2c++exception001.cpp - test whether a POSIX signal can be turned into a C++ exception
Posted by Anonymous on Tue 7th Apr 2026 14:59
raw | new post
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.
rovema.kpaste.net RSS