【问题标题】:printf() prints twice the same line after signal handlingprintf() 在信号处理后打印同一行两次
【发布时间】:2020-09-21 12:37:32
【问题描述】:

我有这个功能(在一个带有信号量的长程序中,如有必要我会附上任何代码):

void signalHandler(int signumber){
    /* for SIGINT */
    if(signumber == SIGINT){    
        printf(" Pressed - Stop the timer & start cleaning process...\n");      
        flag = 0; //relevant for the rest of the program
    }
}

当我运行程序并按CTRL+C 停止它时,而不是得到这个输出:

^C Pressed - Stop the timer & start cleaning process...

*****Timer finished / stopped - clean the queue*****
....

我用双打印得到这个输出:

^C Pressed - Stop the timer & start cleaning process...
 Pressed - Stop the timer & start cleaning process...

*****Timer finished / stopped - clean the queue*****
....

这个小东西很烦人,我该如何解决? 谢谢。

【问题讨论】:

  • printf 不是异步信号安全的,因此在信号处理程序中调用它会产生未定义的行为。不要那样做。
  • stdio 甚至在signal-safety(7)的第三段中被调用...
  • 标签中有标签fork。你在分叉之前设置信号处理程序吗?父母和孩子都收到信号,所以他们都会打印消息。

标签: c linux multiprocessing fork


【解决方案1】:

在 ISO C 中,信号处理程序只能设置 volatile atomic 标志,或中止程序。在 POSIX 中为 may also call some signal-safe functions,您会看到 printf 不在列表中。

所以,基本上,不要从信号处理程序调用 printf。

也许你可以 write 到标准输出,如果要在没有 ISO 一致性的情况下遵循 POSIX 一致性。或者对于后者,在信号处理程序中设置一个标志,并从主循环定期检查该标志。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多