c语言sigaction,使用sigaction(),c
讓我們試著了解修改后的代碼版本會發生什么:
#include
#include
void termination_handler(int signum)
{
printf("Hello from handler\n");
sleep(1);
}
int main (void)
{
//Structs that will describe the old action and the new action
//associated to the SIGINT signal (Ctrl+c from keyboard).
struct sigaction new_action, old_action;
//Set the handler in the new_action struct
new_action.sa_handler = termination_handler;
//Set to empty the sa_mask. It means that no signal is blocked
// while the handler run.
sigemptyset(&new_action.sa_mask);
//Block the SEGTERM signal.
// It means that while the handler run, the SIGTERM signal is ignored
sigaddset(&new_action.sa_mask, SIGTERM);
//Remove any flag from sa_flag. See documentation for flags allowed
new_action.sa_flags = 0;
//Read the old signal associated to SIGINT (keyboard, see signal(7))
sigaction(SIGINT, NULL, &old_action);
//If the old handler wasn't SIG_IGN (it's a handler that just
// "ignore" the signal)
if (old_action.sa_handler != SIG_IGN)
{
//Replace the signal handler of SIGINT with the one described by new_action
sigaction(SIGINT,&new_action,NULL);
}
while(1)
{
printf("In the loop\n");
sleep(100);
}
return 0;
}
因此,如果您編譯并啟動它,然后按Ctrl C,那么您將執行處理程序消息,然后您立即返回主要的睡眠狀態.您可以根據需要多次執行此操作,并且仍會顯示處理程序消息和內聯消息.
因此,您提供了一個函數,sigaction會執行將信號與處理程序掛鉤所需的所有操作.
現在,sigterm怎么樣?如果你在termination_handler中增加了睡眠時間,你可以在按下Ctrl C后鍵入類似“pkill –signal SIGTERM ./a.out”的內容.然后,會發生什么?沒有!在termination_handler運行時,SIGTERM信號被阻止.但是一旦你回到主,現在SIGTERM將殺死應用程序.
(請記住,在測試此代碼時,您仍然可以通過發送SIGKILL信號來終止應用程序.)
如果你想了解更多,并且對信號有更多的樂趣,你可以使用signal manual和sigaction manual來說明更多信息.請注意,您還具有sigaction結構的詳細說明.
總結
以上是生活随笔為你收集整理的c语言sigaction,使用sigaction(),c的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高级程序设计c语言试卷答案,高级程序设计
- 下一篇: c语言编写动画屏保源码,发个C代码(简单