Skip to content

Instantly share code, notes, and snippets.

@jvcleave
Created November 18, 2023 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jvcleave/f964f72f0e0723fec3aa97995cca45b5 to your computer and use it in GitHub Desktop.
Save jvcleave/f964f72f0e0723fec3aa97995cca45b5 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <csignal>
#include <stdexcept>
// Global variable to track whether an exception was thrown
bool exceptionThrown = false;
// Signal handler function
void signalHandler(int signum) {
if (exceptionThrown) {
// Handle the exception here, or perform any necessary cleanup
std::cerr << "Caught an exception during signal handling." << std::endl;
}
// Optionally, re-raise the signal to terminate the program
signal(signum, SIG_DFL);
raise(signum);
}
int main() {
// Register the signal handler
signal(SIGUSR1, signalHandler);
try {
// Your code that uses the library here
// If an exception is thrown, set the global flag
} catch (const std::exception& e) {
std::cerr << "Caught an exception: " << e.what() << std::endl;
exceptionThrown = true;
}
// Continue with normal program execution
// If you want to trigger the signal handler to catch an exception on exit
if (exceptionThrown) {
kill(getpid(), SIGUSR1);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment