【发布时间】:2015-01-02 04:32:25
【问题描述】:
我编写这个程序来捕获 Ctrl-C 和 -\ 或 sigint 和 sigquit 函数,我在评论我对这个程序的作用的理解。如果我错了,您能否纠正我和/或解释发生了什么,以便我能更好地理解?
//
// main.c
// Project 4
//
// Found help with understanding and coding at
// http://www.thegeekstuff.com/2012/03/catch-signals-sample-c-code/
//
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
//signal handling function that will except ctrl-\ and ctrl-c
void sig_handler(int signo)
{
//looks for ctrl-c which has a value of 2
if (signo == SIGINT)
printf("\nreceived SIGINT\n");
//looks for ctrl-\ which has a value of 9
else if (signo == SIGQUIT)
printf("\nreceived SIGQUIT\n");
}
int main(void)
{
//these if statement catch errors
if (signal(SIGINT, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGINT\n");
if (signal(SIGQUIT, sig_handler) == SIG_ERR)
printf("\ncan't catch SIGQUIT\n");
//Runs the program infinitely so we can continue to input signals
while(1)
sleep(1);
return 0;
}
【问题讨论】:
-
仔细阅读 signal(7) 然后使用sigaction(2)
-
阿门,刚刚开始查看它们,已经很清楚了,非常感谢,很好的资源。
-
请注意,禁止从信号处理程序内部调用
printf(原则上)。