c 中 stdout, stderr 容易忽视的一些细节

31 篇文章 0 订阅

先看下面一个例子

a.c :

int main(int argc, char *argv[])
{
	fprintf(stdout, "normal\n");
	fprintf(stderr, "bad\n");
	return 0;
}

$ ./a
normal
bad

$ ./a > tmp 2>&1
$ cat tmp
bad
tmp

我们看到, 重定向到一个文件后, bad 到了 normal 的前面.

原因如下:
"The stream stderr is unbuffered. The stream stdout is line-buffered when it points to a
     terminal. Partial lines will not appear until fflush(3) or exit(3) is called, or a newline
     is printed. This can produce unexpected results, especially with debugging output.  The
     buffering mode of the standard streams (or any other stream) can be changed using the
     setbuf(3) or setvbuf(3) call. "

因此, 可以使用如下的代码:

int main(int argc, char *argv[])
{
	fprintf(stdout, " normal\n");
	fflush(stdout);
	fprintf(stderr, " bad\n");
	return 0;
}
这样重定向到一个文件后就正常了. 但是这种方法只适用于少量的输出, 全局的设置方法还需要用 setbuf() 或 setvbuf(), 或者采用下面的系统调用:

int main(int argc, char *argv[])
{
	write(1, "normal\n", strlen("normal\n"));
	write(2, "bad\n", strlen("bad\n"));
	return 0;
}

但是尽量不要同时使用 文件流 和 文件描述符, 

"Note that mixing use of FILEs and raw file descriptors can produce unexpected results and
     should generally be avoided.  A general rule is that file
     descriptors are handled in the kernel, while stdio is just a library. This means for exam-
     ple, that after an exec(), the child inherits all open file descriptors, but all old
     streams have become inaccessible."



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值