重定向只是把文件描述符指向改掉了,但是标准库中的FILE对象里的缓冲策略并没有变;
|
USER SPACE | KERNEL SPACE
|
+--------------+ | +-----------------+
| FILE *stdout | | +------------+ close----->| fileobj1 urtty |
+--------------+ | |fd 0 + +-----------------+
`--------#-->|fd 1 +-----# +-----------------+
/--------#-->|fd 2 +------\-# close----->| fileobj2 urtty |
+--------------+ | . . \ \ +-----------------+
| FILE *stderr | | . . \ \ +------------------+
+--------------+ | |fd x +---------#-#-->| fileobjx newfile |
| +------------------+
|
|
另外,程序初始化时标准输出的缓冲策略,还跟对应文件的类型有关,如果是tty就是行缓冲,否则为全缓冲;
>file 2>&1 2>&1 >file 什么区别
看一直有人问这个问题,但是大家得到的关于解析顺序的答案 其实并不是事情的真相。
要理解两者真正的区别,先要理解一点基本概念:
"文件描述子和文件对象之间的关系"
"dup(2) dup2(2)两个系统调用的作用"
参考stevens大爷的优秀叙事风格之一"图解法",画了几个text图给大家,方便大家理解:
>newfile 2>&1
+-----------------+
+------------+ #------>| fileobj1 urtty |
|fd 0 + / +-----------------+
|fd 1 +-----# +-----------------+
|fd 2 +-------------->| fileobj2 urtty |
. . +-----------------+
. . +-----------------+
|fd x +-------------->| fileobjx newfile|
+-----------------+
>newfile dup2(fdx, fd1);
+-----------------+
+------------+ close----->| fileobj1 urtty |
|fd 0 + +-----------------+
|fd 1 +-----# +-----------------+
|fd 2 +------\------->| fileobj2 urtty |
. . \ +-----------------+
. . \ +-----------------+
|fd x +---------#---->| fileobjx newfile|
+-----------------+
2>&1 dup2(fd1, fd2);
+-----------------+
+------------+ close----->| fileobj1 urtty |
|fd 0 + +-----------------+
|fd 1 +-----# +-----------------+
|fd 2 +------\-# close----->| fileobj2 urtty |
. . \ \ +-----------------+
. . \ \ +-----------------+
|fd x +---------#-#-->| fileobjx newfile|
+-----------------+
-----------------------------------------------------------------------
2>&1 >newfile:
+-----------------+
+------------+ #------>| fileobj1 urtty |
|fd 0 + / +-----------------+
|fd 1 +-----# +-----------------+
|fd 2 +-------------->| fileobj2 urtty |
. . +-----------------+
. . +-----------------+
|fd x +-------------->| fileobjx newfile|
+-----------------+
2>&1 dup2(fd1, fd2);
+-----------------+
+------------+ #-#---->| fileobj1 urtty |
|fd 0 + / / +-----------------+
|fd 1 +-----# / +-----------------+
|fd 2 +------# close----->| fileobj2 urtty |
. . +-----------------+
. . +-----------------+
|fd x +-------------->| fileobjx newfile|
+-----------------+
>newfile dup2(fdx, fd1);
+-----------------+
+------------+ #---->| fileobj1 urtty | 引用计数不为0,不释放
|fd 0 + / +-----------------+
|fd 1 +---# / +-----------------+
|fd 2 +----\-# close----->| fileobj2 urtty |
. . \ +-----------------+
. . \ +-----------------+
|fd x +-------#------>| fileobjx newfile|
+-----------------+
阅读(1077) | 评论(0) | 转发(0) |