// C++可处理的信号 // SIGABRT: 程序的异常终止,如调用 abort。 // SIGFPE: 错误的算术运算,比如除以零或导致溢出的操作。 // SIGILL: 检测非法指令。 // SIGINT: 接收到交互注意信号。 // SIGSEGV: 非法访问内存。 // SIGTERM: 发送到程序的终止请求。 // SIGBUS: Bus error which indicates access to an invalid address // SIGALRM: This is used by the alarm() function and indicates the expiration of the timer. 超时警告 // SIGABRT: Termination of a program, abnormally // SIGSTOP: The signal cannot be blocked, handled, and ignored and can stop a process // SIGUSR1: 用户定义信号 // SIGSUR2: 用户定义信号 // 用法: // void (*signal (int sig, void (*func)(int)))(int); // signal(registered signal, signal handler) #include #include #include using namespace std; // 定义信号处理函数 // 必须是 void func(int) 的形式 void signalHandler(int signum) { cout << "Interrupt signal (" << signum << ") received." << endl; // 清理并关闭 // 终止程序 exit(signum); } int main() { // 注册信号 SIGINT 和信号处理程序 signal(SIGINT, signalHandler); while(true) { cout << "Going to sleep...." << endl; sleep(1); } return 0; }