linux

C++如何处理Linux下的信号与异常

小樊
48
2025-06-11 19:02:59
栏目: 编程语言

在C++中,处理Linux下的信号和异常主要涉及到两个方面:信号处理(signal handling)和异常处理(exception handling)。下面分别介绍这两个方面的处理方法。

信号处理(Signal Handling)

信号是Linux系统中的一种异步通知机制,用于通知进程发生了某个事件。在C++中,可以使用signal函数或者更高级的sigaction函数来处理信号。

使用signal函数

#include <csignal>
#include <iostream>

void signal_handler(int signum) {
    std::cout << "Received signal: " << signum << std::endl;
}

int main() {
    // 注册信号处理器
    std::signal(SIGINT, signal_handler); // 处理Ctrl+C信号
    std::signal(SIGTERM, signal_handler); // 处理终止信号

    std::cout << "Press Ctrl+C or send a SIGTERM signal to terminate the program." << std::endl;

    // 主循环
    while (true) {
        // ...
    }

    return 0;
}

使用sigaction函数

#include <csignal>
#include <iostream>

void signal_handler(int signum) {
    std::cout << "Received signal: " << signum << std::endl;
}

int main() {
    struct sigaction sa;
    sa.sa_handler = signal_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;

    // 注册信号处理器
    sigaction(SIGINT, &sa, NULL); // 处理Ctrl+C信号
    sigaction(SIGTERM, &sa, NULL); // 处理终止信号

    std::cout << "Press Ctrl+C or send a SIGTERM signal to terminate the program." << std::endl;

    // 主循环
    while (true) {
        // ...
    }

    return 0;
}

异常处理(Exception Handling)

C++中的异常处理主要使用trycatchthrow关键字。当程序遇到错误时,可以抛出一个异常,然后在适当的地方捕获并处理该异常。

#include <iostream>
#include <stdexcept>

int divide(int a, int b) {
    if (b == 0) {
        throw std::runtime_error("Division by zero");
    }
    return a / b;
}

int main() {
    try {
        int result = divide(10, 0);
        std::cout << "Result: " << result << std::endl;
    } catch (const std::runtime_error& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}

在这个例子中,当divide函数遇到除数为0的情况时,会抛出一个std::runtime_error异常。在main函数中,我们使用try块来调用divide函数,并使用catch块来捕获并处理异常。

注意:信号处理和异常处理是两个不同的概念。信号处理主要用于处理操作系统发出的异步事件,而异常处理主要用于处理程序运行时的错误。在实际编程中,应根据具体情况选择合适的处理方法。

0
看了该问题的人还看了