[英]printf() prints twice the same line after signal handling
I have this function (in a long program with semaphores, I'll attach any code if necessary):我有这个 function (在带有信号量的长程序中,如有必要,我将附上任何代码):
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
}
}
when I'm running the program and press CTRL+C
to stop it, instead of getting this output:当我运行程序并按
CTRL+C
停止它时,而不是得到这个 output:
^C Pressed - Stop the timer & start cleaning process...
*****Timer finished / stopped - clean the queue*****
....
I get this output with double print:我得到这个带有双打印的 output:
^C Pressed - Stop the timer & start cleaning process...
Pressed - Stop the timer & start cleaning process...
*****Timer finished / stopped - clean the queue*****
....
This little thing very annoying, how can I fix it?这个小东西很烦人,我该如何解决? Thanks.
谢谢。
In ISO C, a signal handler may only set a volatile atomic flag, or abort the program.在 ISO C 中,信号处理程序只能设置易失原子标志,或中止程序。 In POSIX it may also call some signal-safe functions , you will see that
printf
is not in the list.在 POSIX 中它也可能调用一些信号安全函数,你会看到
printf
不在列表中。
So, basically, don't call printf from the signal handler.所以,基本上,不要从信号处理程序中调用 printf 。
Perhaps you could write
to stdout, if going for POSIX conformance without ISO conformance.如果要在没有 ISO 一致性的情况下遵循 POSIX 一致性,也许您可以
write
标准输出。 Or for the latter, set a flag in the signal handler and check that flag periodically from the main loop.或者对于后者,在信号处理程序中设置一个标志并从主循环定期检查该标志。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.