C: SIGALRM - 每秒显示消息的警报

标签 c alarm

因此,我尝试调用警报以每秒显示一条消息“仍在工作......”。 我包含了 signal.h。

在我的 main 之外,我有我的功能:(我从不为 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);
}

然后,在我的主要

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

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

最佳答案

信号处理程序不应包含“业务逻辑”或进行库调用,例如 printf。参见 C11 §7.1.4/4 及其脚注:

Thus, a signal handler cannot, in general, call standard library functions.

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

#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\n" );
            print_flag = false;
            alarm( 1 ); // Reschedule.
        }
    }
}

关于C: SIGALRM - 每秒显示消息的警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21542077/

相关文章:

java - 关闭应用程序后,Android AlarmManager 在某些设备上不起作用

c - C 中只有单行输出而不是多行输出(if/else 和组合)

c 程序绕过 gets()

iphone - 设备锁定时响应事件

android - 在 Android 中安排操作或警报

c - 当信号到达时警报停止

android - getExtra from Intent 从一个 pendingIntent 启动

c - Windows 操作系统中命名信号量的位置是什么

c - 失效进程,fork()

c - makefile 返回缺少的分隔符