C: SIGALRM - 每秒显示消息的警报 [英] C: SIGALRM - alarm to display message every second

查看:29
本文介绍了C: SIGALRM - 每秒显示消息的警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图呼叫警报以每秒显示一条消息仍在工作......".我包括了signal.h.

So I'm trying to call an alarm to display a message "still working.." every second. I included signal.h.

在我的 main 之外,我有我的函数:(我从不为 int 声明/定义 s)

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...
" );
     alarm(1);    //for every second
     signal(SIGALRM, display_message);
}

然后,在我的主要

while(1)
{
    signal(SIGALRM, display_message);
    alarm(1);     //Alarm signal every second.

循环一开始就在那里.但是该程序从不输出仍在工作..."消息.我做错了什么?谢谢,非常感谢.

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.

信号处理程序应该做的就是设置一个标志以供非中断代码执行,并解除等待系统调用的阻塞.即使添加了某些 I/O 或其他功能,该程序也能正确运行并且不会有崩溃的风险:

All the signal handler should do is set a flag to be acted upon by non-interrupt code, and unblock a waiting system call. This program runs correctly and does not risk crashing, even if some I/O or 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 (;;) {
        sleep( 5 ); // Pretend to do something. Could also be read() or select().
        if ( print_flag ) {
            printf( "Hello
" );
            print_flag = false;
            alarm( 1 ); // Reschedule.
        }
    }
}

这篇关于C: SIGALRM - 每秒显示消息的警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆