W3Cschool
恭喜您成為首批注冊(cè)用戶(hù)
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
信號(hào)是由操作系統(tǒng)傳給進(jìn)程的中斷,會(huì)提早終止一個(gè)程序。在 UNIX、LINUX、Mac OS X 或 Windows 系統(tǒng)上,可以通過(guò)按 Ctrl+C 產(chǎn)生中斷。
有些信號(hào)不能被程序捕獲,但是下表所列信號(hào)可以在程序中捕獲,并可以基于信號(hào)采取適當(dāng)?shù)膭?dòng)作。這些信號(hào)是定義在 C++ 頭文件 <csignal> 中。
信號(hào) | 描述 |
---|---|
SIGABRT | 程序的異常終止,如調(diào)用 abort。 |
SIGFPE | 錯(cuò)誤的算術(shù)運(yùn)算,比如除以零或?qū)е乱绯龅牟僮鳌?/td> |
SIGILL | 檢測(cè)非法指令。 |
SIGINT | 接收到交互注意信號(hào)。 |
SIGSEGV | 非法訪問(wèn)內(nèi)存。 |
SIGTERM | 發(fā)送到程序的終止請(qǐng)求。 |
C++ 信號(hào)處理庫(kù)提供了 signal 函數(shù),用來(lái)捕獲突發(fā)事件。以下是 signal() 函數(shù)的語(yǔ)法:
void (*signal (int sig, void (*func)(int)))(int);
這個(gè)函數(shù)接收兩個(gè)參數(shù):第一個(gè)參數(shù)是一個(gè)整數(shù),代表了信號(hào)的編號(hào);第二個(gè)參數(shù)是一個(gè)指向信號(hào)處理函數(shù)的指針。
讓我們編寫(xiě)一個(gè)簡(jiǎn)單的 C++ 程序,使用 signal() 函數(shù)捕獲 SIGINT 信號(hào)。不管您想在程序中捕獲什么信號(hào),您都必須使用 signal 函數(shù)來(lái)注冊(cè)信號(hào),并將其與信號(hào)處理程序相關(guān)聯(lián)??纯聪旅娴膶?shí)例:
#include <iostream>
#include <csignal>
#include <unistd.h>
using namespace std;
void signalHandler( int signum )
{
cout << "Interrupt signal (" << signum << ") received.\n";
// 清理并關(guān)閉
// 終止程序
exit(signum);
}
int main ()
{
// 注冊(cè)信號(hào) SIGINT 和信號(hào)處理程序
signal(SIGINT, signalHandler);
while(1){
cout << "Going to sleep...." << endl;
sleep(1);
}
return 0;
}
當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果:
Going to sleep.... Going to sleep.... Going to sleep....
現(xiàn)在,按 Ctrl+C 來(lái)中斷程序,您會(huì)看到程序捕獲信號(hào),程序打印如下內(nèi)容并退出:
Going to sleep.... Going to sleep.... Going to sleep.... Interrupt signal (2) received.
您可以使用函數(shù) raise() 生成信號(hào),該函數(shù)帶有一個(gè)整數(shù)信號(hào)編號(hào)作為參數(shù),語(yǔ)法如下:
int raise (signal sig);
在這里,sig 是要發(fā)送的信號(hào)的編號(hào),這些信號(hào)包括:SIGINT、SIGABRT、SIGFPE、SIGILL、SIGSEGV、SIGTERM、SIGHUP。以下是我們使用 raise() 函數(shù)內(nèi)部生成信號(hào)的實(shí)例:
#include <iostream>
#include <csignal>
using namespace std;
void signalHandler( int signum )
{
cout << "Interrupt signal (" << signum << ") received.\n";
// 清理并關(guān)閉
// 終止程序
exit(signum);
}
int main ()
{
int i = 0;
// 注冊(cè)信號(hào) SIGINT 和信號(hào)處理程序
signal(SIGINT, signalHandler);
while(++i){
cout << "Going to sleep...." << endl;
if( i == 3 ){
raise( SIGINT);
}
sleep(1);
}
return 0;
}
當(dāng)上面的代碼被編譯和執(zhí)行時(shí),它會(huì)產(chǎn)生下列結(jié)果,并會(huì)自動(dòng)退出:
Going to sleep.... Going to sleep.... Going to sleep.... Interrupt signal (2) received.
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: