在C++ Linux編程中,處理信號(signals)是一種常見的需求,因為它們允許程序響應各種系統事件,如中斷、終止請求等。以下是處理信號的基本步驟和示例代碼:
首先,你需要包含處理信號所需的頭文件:
#include <csignal>
#include <iostream>
定義一個函數來處理特定的信號。這個函數的原型通常是:
void signalHandler(int signum);
其中 signum
是接收到的信號編號。
使用 signal
或 sigaction
函數來注冊信號處理函數。sigaction
提供了更細粒度的控制,推薦使用。
signal
函數#include <csignal>
#include <iostream>
void signalHandler(int signum) {
std::cout << "Interrupt signal (" << signum << ") received.\n";
// 清理并關閉
// 終止程序
exit(signum);
}
int main() {
// 注冊信號 SIGINT 的處理函數
signal(SIGINT, signalHandler);
std::cout << "Program is running. Press Ctrl+C to interrupt.\n";
while (true) {
// 主循環
}
return 0;
}
sigaction
函數#include <csignal>
#include <iostream>
void signalHandler(int signum) {
std::cout << "Interrupt signal (" << signum << ") received.\n";
// 清理并關閉
// 終止程序
exit(signum);
}
int main() {
struct sigaction sa;
sa.sa_handler = signalHandler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
// 注冊信號 SIGINT 的處理函數
if (sigaction(SIGINT, &sa, NULL) == -1) {
perror("sigaction");
exit(EXIT_FAILURE);
}
std::cout << "Program is running. Press Ctrl+C to interrupt.\n";
while (true) {
// 主循環
}
return 0;
}
你可以為不同的信號注冊不同的處理函數。例如:
#include <csignal>
#include <iostream>
void signalHandlerSIGINT(int signum) {
std::cout << "SIGINT signal (" << signum << ") received.\n";
}
void signalHandlerSIGTERM(int signum) {
std::cout << "SIGTERM signal (" << signum << ") received.\n";
}
int main() {
struct sigaction saSIGINT, saSIGTERM;
saSIGINT.sa_handler = signalHandlerSIGINT;
sigemptyset(&saSIGINT.sa_mask);
saSIGINT.sa_flags = 0;
saSIGTERM.sa_handler = signalHandlerSIGTERM;
sigemptyset(&saSIGTERM.sa_mask);
saSIGTERM.sa_flags = 0;
if (sigaction(SIGINT, &saSIGINT, NULL) == -1) {
perror("sigaction SIGINT");
exit(EXIT_FAILURE);
}
if (sigaction(SIGTERM, &saSIGTERM, NULL) == -1) {
perror("sigaction SIGTERM");
exit(EXIT_FAILURE);
}
std::cout << "Program is running. Press Ctrl+C or send SIGTERM to terminate.\n";
while (true) {
// 主循環
}
return 0;
}
printf
、malloc
等)。sigprocmask
函數來屏蔽某些信號,以防止它們在關鍵代碼段中被處理。通過以上步驟,你可以在C++ Linux編程中有效地處理信號。