gpt4 book ai didi

c - 未打印信号处理程序语句

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:49 25 4
gpt4 key购买 nike

在检查信号时,我发现处理程序中的语句没有被打印出来。这是我使用的代码:

#include"stdio.h"
#include"signal.h"
#include"unistd.h"
void handlerSIGINT(int sig)
{
if(sig == SIGINT)
printf("\nFinally caught SIGINT...");
}
int main()
{
printf("Hello ... soon u'll receive a signal");
if(signal(SIGINT, handlerSIGINT) == SIG_ERR)
{
printf("error in SIGINT handling");
}
while(1)
sleep(1);
/*now press control + C to see the effect */
return 0;
}

运行程序时得到如下输出:

[root@node1 mytest]# ./a.out
^CHello ... soon u'll receive a signal
^CFinally caught SIGINT...
^CFinally caught SIGINT...
^CFinally caught SIGINT...
^Z
[1]+ Stopped ./a.out

我的困惑是:当我第一次按下“Ctrl+C”时,它没有在处理程序中打印消息,即“Finally caught SIGINT...”。但是从第二次开始打印消息。谁能解释为什么会这样……

最佳答案

void handlerSIGINT(int sig)
{
if (sig == SIGINT)
printf("\nFinally caught SIGINT...");
}

在信号处理程序中,输出没有被新行终止,默认情况下,标准输出是行缓冲的,所以它只在下次看到 \n 时显示在一开始的时候。将其更改为:

printf("Finally caught SIGINT...\n");

您可能会看到预期的结果。但是请注意,you should avoid using printf in a signal handler .

关于c - 未打印信号处理程序语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24446002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com