标准缓冲区在系统()调用之前没有被清除
#include<stdio.h>
#include<signal.h>
#include<stdlib.h>
void handler(int signo)
{
printf("First statement");
system("date");
exit(EXIT_SUCCESS);
}
int main()
{
signal(SIGINT,handler);
printf("Waiting for KeyboardInterrupt\n");
for(;;);
return 0;
}
测试运行:-
shadyabhi@shadyabhi-desktop:~/c$ gcc main.c
shadyabhi@shadyabhi-desktop:~/c$ ./a.out
Waiting for KeyboardInterrupt
^CWed Mar 10 23:55:47 IST 2010
First statementshadyabhi@shadyabhi-desktop:~/c$
为什么在 system() 调用后打印“First Statement”?
#include<stdio.h>
#include<signal.h>
#include<stdlib.h>
void handler(int signo)
{
printf("First statement");
system("date");
exit(EXIT_SUCCESS);
}
int main()
{
signal(SIGINT,handler);
printf("Waiting for KeyboardInterrupt\n");
for(;;);
return 0;
}
Test run:-
shadyabhi@shadyabhi-desktop:~/c$ gcc main.c
shadyabhi@shadyabhi-desktop:~/c$ ./a.out
Waiting for KeyboardInterrupt
^CWed Mar 10 23:55:47 IST 2010
First statementshadyabhi@shadyabhi-desktop:~/c$
Why is "First Statement" getting printed after system() call??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C IO API 会缓冲内容以便更有效地打印。通常,每当您写出换行符或手动刷新缓冲区时,缓冲区都会被刷新。
因此,您可以使用换行符来刷新缓冲区:
或者使用 fflush 函数:
The C IO API buffers things up in order to print more efficiently. Typically the buffer is flushed whenever you write out a newline or manually flush it.
So you can use a newline to flush the buffer:
Or use the fflush function:
标准输入、输出和错误流是在进程启动时创建的,在本例中是 C 程序。当您进行系统调用时,会创建另一个进程来执行日期命令,并获得自己的一组流。
在您的程序中,printf 输出被缓冲到 C 程序的标准输出流。然后日期的输出被缓冲到它自己的标准输出流。当系统调用结束时,日期标准输出流将被刷新,以便您看到输出。然后,当您的 C 程序结束时,其标准输出流将被刷新,您将看到 printf 输出。
您可能会发现此人的帖子很有帮助:http://www.pixelbeat.org/programming/stdio_buffering/< /a>
The standard input, output and error streams are created when your process starts, which in this case is your C program. When you make the system call, another process is created to execute the date command, and it gets its own set of streams.
In your program, the printf output is buffered to the standard output stream of your C program. Then the output of date is buffered to its own standard output stream. When the system call ends, the date standard output stream is flushed, so you see the output. Then, when your C program ends, its standard output stream is flushed and you see the printf output.
You might find this fellow's posting helpful: http://www.pixelbeat.org/programming/stdio_buffering/
您是否在调用 system("date") 之前尝试刷新缓冲区?
我刚刚在
system
之前添加了fflush(NULL);
,输出符合预期。Did you try flushing the buffer before calling system("date")?
I just added
fflush(NULL);
beforesystem
, and the output is as expected.