printf() 在信号处理后打印两次同一行

bin*_*min 0 c linux fork multiprocessing

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行程序并按下CTRL+C停止它时,而不是获得以下输出:

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

*****Timer finished / stopped - clean the queue*****
....
Run Code Online (Sandbox Code Playgroud)

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

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

*****Timer finished / stopped - clean the queue*****
....
Run Code Online (Sandbox Code Playgroud)

这个小东西很烦人,怎么解决?谢谢。

M.M*_*M.M 5

在 ISO C 中,信号处理程序只能设置 volatile 原子标志,或中止程序。在 POSIX 中它也可能调用一些信号安全函数,你会看到它printf不在列表中。

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

也许你可以write标准输出,如果不符合 ISO 符合 POSIX 一致性。或者对于后者,在信号处理程序中设置一个标志并定期从主循环中检查该标志。