看一直有人问这个问题,但是大家得到的关于解析顺序的答案 其实并不是事情的真相。
要理解两者真正的区别,先要理解一点基本概念:
"文件描述子和文件对象之间的关系"
"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|
+-----------------+
阅读(1882) | 评论(1) | 转发(0) |