- 信號(hào)(signal)是一種軟件中斷,它提供了一種處理異步事件的方法办素,也是進(jìn)程間惟一的異步通信方式。信號(hào)可由硬件中斷(按下組合鍵/除0/無效的存儲(chǔ)訪問)或軟中斷(進(jìn)程調(diào)用kill或sigqueue發(fā)送信號(hào))產(chǎn)生
#include <csignal>
#include <iostream>
#include <unistd.h>
#include <time.h>
using namespace std;
void signalUsr1Handler(int signum) {
cout << "interrup signal: " << signum << " received." << endl;
//exit(signum);
}
void signalKillHandler(int signum) {
cout << "signal kill: " << signum << " received." << endl;
}
int main(int argc, char* argv[]) {
signal(SIGUSR1, signalUsr1Handler);
signal(SIGKILL, signalKillHandler);
while(1) {
const time_t now = time(NULL);
cout << asctime(localtime(&now)) << "going to sleep..." << endl;
sleep(3);
}
//cout << "going to pause..." << endl;
//pause();
//
return 0;
}
依次發(fā)送kill -SIGUSR1 24021和kill -SIGKILL 20241可得到
上面的示例中璧亚,盡管注冊了SIGKILL的處理函數(shù)砰识,并不起作用谴供,是因?yàn)镾IGKILL和SIGSTOP這兩個(gè)信號(hào)不能被忽略块茁,同時(shí)這兩個(gè)信號(hào)也不能被捕獲和阻塞。
另外:pause:將進(jìn)程掛起等待信號(hào)桂肌,直到信號(hào)到來数焊,才會(huì)繼續(xù)處理