遇到过这样的问题:
程序源码:
原因是:stdout和stderr是不同的设备描述符,stdout是块设备,而stderr不是。对于块设备,只有遇到下面几种情况才会输出:1)遇到回车,2)缓冲区满,3)flush被调用。而stderr不会,stderr是标准错误,直接输出。
下面说以下几种设备的缓冲:
标准输入,输出是行缓冲,Line buffering is typically used on a stream when it refers to a terminal: standard input and standard output, for example.
举例来说就是你,printf(stdout, "xxxx"); 而不是printf(stdout, "xxxx\n"),前者会憋住,直到遇到新行才会一起输出
printf(stderr, "xxxxx"),不管有么有\n,都输出。
标准错误是无缓冲。
stdout,stdin是全缓冲。
程序源码:
//filename: 1_test.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
while( 1 ) {
fprintf( stdout, "hello-std-out" );
fprintf( stderr, "hello-std-err" );
sleep( 1 );
}
return 0;
}
输出结果大家应该都已经猜到了:
开始一直输出hello-std-err,当stdout的缓冲区满后,一次输出hello-std-out,接着重复以上动作。原因是:stdout和stderr是不同的设备描述符,stdout是块设备,而stderr不是。对于块设备,只有遇到下面几种情况才会输出:1)遇到回车,2)缓冲区满,3)flush被调用。而stderr不会,stderr是标准错误,直接输出。
下面说以下几种设备的缓冲:
标准输入,输出是行缓冲,Line buffering is typically used on a stream when it refers to a terminal: standard input and standard output, for example.
举例来说就是你,printf(stdout, "xxxx"); 而不是printf(stdout, "xxxx\n"),前者会憋住,直到遇到新行才会一起输出
printf(stderr, "xxxxx"),不管有么有\n,都输出。
标准错误是无缓冲。
stdout,stdin是全缓冲。