C:SIGALRM - 报警信息显示每秒 [英] C: SIGALRM - alarm to display message every second
问题描述
所以我想打电话报警,显示信息仍然在工作。每一秒钟。
我包括signal.h中。
So I'm trying to call an alarm to display a message "still working.." every second. I included signal.h.
我主外,我有我的功能:(我从来没有申报/定义S表示的int)
Outside of my main I have my function: (I never declare/define s for int s)
void display_message(int s); //Function for alarm set up
void display_message(int s) {
printf("copyit: Still working...\n" );
alarm(1); //for every second
signal(SIGALRM, display_message);
}
然后,在我的主要
Then, in my main
while(1)
{
signal(SIGALRM, display_message);
alarm(1); //Alarm signal every second.
这只要循环开始的在那里。但该计划从未输出仍在工作......消息。我在做什么错误?谢谢你,多版本AP preciated。
That's in there as soon as the loop begins. But the program never outputs the 'still working...' message. What am I doing incorrectly? Thank you, ver much appreciated.
推荐答案
信号处理是不应该含有商业逻辑,或让库调用,如的printf
。见C11§7.1.4/ 4和脚注:
Signal handlers are not supposed to contain "business logic" or make library calls such as printf
. See C11 §7.1.4/4 and its footnote:
因此,信号处理程序不是在一般情况下,调用标准库函数。
Thus, a signal handler cannot, in general, call standard library functions.
所有的信号处理程序应该做的是设置为通过非中断code采取行动的标志。该程序运行正常,并没有崩溃的风险,即使是增加了一些I / O的其他功能:
All the signal handler should do is set a flag to be acted upon by non-interrupt code. This program runs correctly and does not risk crashing, even if some I/O other functionality were added:
#include <signal.h>
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
volatile sig_atomic_t print_flag = false;
void handle_alarm( int sig ) {
print_flag = true;
}
int main() {
signal( SIGALRM, handle_alarm ); // Install handler first,
alarm( 1 ); // before scheduling it to be called.
for (;;) {
if ( print_flag ) {
printf( "Hello\n" );
print_flag = false;
alarm( 1 );
}
}
}
请注意,虽然,旋转循环是编程一个可怕的方式。本例中使用100%的CPU电力,因为它从来不睡觉。此外报警
没有出现,虽然POSIX将其标记为这样的,我记得这是K&安培的一部分要由C标准定义; R。因此,在便携性方面,你会一样好了与另一个POSIX设施。
Note, though, that spin loops are an awful way to program. This example uses 100% CPU power because it never sleeps. Furthermore alarm
does not appear to be defined by the C standard although POSIX marks it as such and I recall it was part of K&R. So in terms of portability, you would be just as well off with another POSIX facility.
这篇关于C:SIGALRM - 报警信息显示每秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!