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.
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;
}
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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?