当前位置: 技术问答>linux和unix
发现一个非常奇怪的问题
来源: 互联网 发布时间:2016-09-05
本文导语: #include #include #define INPUTLEN 100 main ( int argc, char *argv[] ) { void inthandler(int); int nchars; char input[INPUTLEN]; signal(SIGINT, inthandler); do{ printf("nType some messagen"); nchars = read(0, input, (INPUTLEN - 1)); if (nchars == -1) { ...
#include
#include
#define INPUTLEN 100
main ( int argc, char *argv[] )
{
void inthandler(int);
int nchars;
char input[INPUTLEN];
signal(SIGINT, inthandler);
do{
printf("nType some messagen");
nchars = read(0, input, (INPUTLEN - 1));
if (nchars == -1)
{
perror("read return an error");
}
else
{
input[nchars] = '';
printf("you typed: %s", input);
}
}while (strncmp(input, "quit", 4) != 0);
return 0;
} /* ---------- end of function main ---------- */
void inthandler(int s)
{
printf("inn");
sleep(2);
printf("outn");
} /* ----- end of function inthandler ----- */
以上程序按下ctrl+c会有立即有in(隔两秒) out的输出,并且都是正常的,
但是把
void inthandler(int s)
{
printf("in");
sleep(2);
printf("out");
}
这个函数就是把in和out的n去掉,结果却大不一样,不立即输出in和out,非常的奇怪。
我类似的两个代码写的一摸一样,就是结果不一样,找了一下午才找到这个细小的差别,甚是不解阿
我的系统是ubuntu9.多的
|
这不奇怪,
printf 函数是有 缓冲区的,也就是说,内容不会立即输出,
一般遇到 n 或者你 自己调用 fflush(stdout);
就会立即刷新,或者说处处。
printf 函数是有 缓冲区的,也就是说,内容不会立即输出,
一般遇到 n 或者你 自己调用 fflush(stdout);
就会立即刷新,或者说处处。
|
之前有人回答过类似问题,很详细,参见:
http://topic.csdn.net/u/20081216/12/117ef250-8acd-432d-a063-e862c8910102.html
http://topic.csdn.net/u/20081216/12/117ef250-8acd-432d-a063-e862c8910102.html
|
好像c++里的cout也是这样?
我记得以前谁问过
|
是的,所以还是fprintf来的实在,有数据立即输出。。。