简单的信号 - C编程及报警功能 [英] Simple Signals - C programming and alarm function
问题描述
#include <stdio.h>
#include <signal.h>
void ALARMhandler(int sig)
{
signal(SIGALRM, SIG_IGN); /* ignore this signal */
printf("Hello");
signal(SIGALRM, ALARMhandler); /* reinstall the handler */
}
int main(int argc, char *argv[])
{
alarm(2); /* set alarm clock */
while (1)
;
printf("All done");
}
我希望该计划到2秒后打印你好,而是输出的zsh:报警./a.out
I expect the program to print "hello" after 2 seconds, but instead the output is "zsh: alarm ./a.out"
任何想法是怎么回事?
推荐答案
你忘了最初设定的报警处理程序。改变的开始的main()
这样的:
You're forgetting to set the alarm handler initially. Change the start of main()
like:
int main(int argc, char *argv[])
{
signal(SIGALRM, ALARMhandler);
...
此外,信号处理程序可能会打印什么。这是因为C库高速缓存输出,直到它看到一行结束。所以:
Also, the signal handler will probably print nothing. That's because the C library caches output until it sees an end of line. So:
void ALARMhandler(int sig)
{
signal(SIGALRM, SIG_IGN); /* ignore this signal */
printf("Hello\n");
signal(SIGALRM, ALARMhandler); /* reinstall the handler */
}
有关现实世界的计划,从信号处理印刷也不是很安全。一个信号处理器应该做的少,因为它可以,preferably只有在这里或那里设置一个标志。和国旗应该声明挥发性
。
For a real-world program, printing from a signal handler is not very safe. A signal handler should do as little as it can, preferably only setting a flag here or there. And the flag should be declared volatile
.
这篇关于简单的信号 - C编程及报警功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!