printf()在信号处理后打印两次相同的行。

问题描述 投票:0回答:1

我有这样一个功能(在一个长的有符号的程序中,如果需要的话,我会附上任何代码)。

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*****
....

这个小东西很烦人,我怎么才能解决它呢?

c linux multiprocessing fork
1个回答
5
投票

在ISO C中,信号处理程序只能设置一个不稳定的原子标志,或者中止程序。 在POSIX中,它 也可以调用一些信号安全函数你会发现 printf 不在列表中。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.