How do I handle signals and exceptions on Linux in C++?

Handling signals and exceptions in C++ on Linux involves using the signal handling library and understanding how to manage exceptions properly. In Linux, signals are software interrupts that can be sent to a process to notify it of various events, while exceptions are used in C++ to handle errors in a more structured way.

Handling Signals in C++

To handle signals, you can use the `signal()` function provided by the C standard library. Here's an example of how to set up a signal handler for `SIGINT`, which is sent when you press Ctrl+C:

#include #include #include void signalHandler(int signum) { std::cout << "Interrupt signal (" << signum << ") received.\n"; exit(signum); } int main() { signal(SIGINT, signalHandler); while (true) { std::cout << "Running...\n"; sleep(1); } return 0; }

Handling Exceptions in C++

In C++, exceptions are handled using the `try`, `catch`, and `throw` keywords. Here's an example demonstrating how to catch an exception:

#include #include void mayThrow() { throw std::runtime_error("Error occurred"); } int main() { try { mayThrow(); } catch (const std::runtime_error& e) { std::cout << "Caught a runtime_error: " << e.what() << '\n'; } return 0; }

C++ Linux signals exceptions signal handling exception handling SIGINT signal handler runtime error