Linux 输出重定向是否按顺序写入stdout和stderr信息?

Linux 输出重定向是否按顺序写入stdout和stderr信息?,linux,shell,io-redirection,Linux,Shell,Io Redirection,我编写了一个程序capture,它输出stdout消息和stderr消息(即printf(),fprintf(stderr,…) 我希望打印信息显示在终端上,并保存到日志文件中 ./capture 2>&1|tee log 但是我看到stdout和stderr消息在日志文件中似乎没有顺序 ./capture 2>&1|tee log 输出重定向是否按顺序写入stdout和stderr信息? 如果没有,我该怎么做才能使它们有序呢?输出重定向按原样保持writ

我编写了一个程序
capture
,它输出stdout消息和stderr消息(即printf(),fprintf(stderr,…)

我希望打印信息显示在终端上,并保存到日志文件中

  ./capture 2>&1|tee log
但是我看到stdout和stderr消息在日志文件中似乎没有顺序

  ./capture 2>&1|tee log
输出重定向是否按顺序写入stdout和stderr信息?
如果没有,我该怎么做才能使它们有序呢?

输出重定向按原样保持
write()
调用的顺序。重定向仅更改为进程保留的内核中的文件描述符结构,将值从
fd1
下复制到
fd2

您的问题是
*printf()
缓冲了批处理一些
write()
调用的输出。通常不使用
stderr的缓冲
stdout的
行缓冲
。但是,当您将其重定向到管道中时,它会切换到
block
缓冲
stdout
,从而延迟输出(请参见
manstdout
)。使用
setlinebuf(stdout)手动将缓冲模式转为line开头,或使用
fflush(stdout)*printf()
后的code>。或者只使用原始
write()
调用。您可以在
man setlinebuf
中了解这一点

实际上,在bash中,您也可以使用
|&
进行重定向。查看
manbash
关于
Pipelines