#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” ?
最佳答案
在您的过程开始时创建标准的输入,输出和错误流,在本例中为C程序。当您进行系统调用时,将创建另一个进程来执行date命令,并且它将获得自己的一组流。
在您的程序中,printf输出被缓冲到C程序的标准输出流。然后,日期输出被缓冲到其自己的标准输出流中。当系统调用结束时,日期标准输出流将被刷新,因此您将看到输出。然后,当C程序结束时,将刷新其标准输出流,并看到printf输出。
您可能会发现此人的帖子很有帮助:http://www.pixelbeat.org/programming/stdio_buffering/
关于c - 在调用system()之前未清除标准缓冲区,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2419508/