首页 > 解决方案 > 在 shell 中复制描述符时 >& 和 <& 是否等效?

问题描述

这篇文章中,作者在评论中说:

<& 或 >& 语法都使用 dup(2) 或类似方法来克隆文件描述符。唯一的区别是 >& 检查目标文件描述符是否打开以供写入,而 <& 检查目标文件描述符是否打开以供读取。在其默认模式下,一个套接字对读写都是打开的,因此两个检查都成功,并且在任何一种情况下 dup 调用都是相同的。

我已经测试了普通文件和 /dev/tcp 套接字的复制描述符。两个运算符都没有区别,重定向 std* 描述符时唯一重要的是打开文件时指定的 r/w 权限。并且bash 参考第 3.6.8 节也说这两个只有当它们的 lhs 参数被省略时才不同。

我的问题是:上面引用中的“检查读/写可访问性”部分是否真的存在,或者我上面的一些想法是错误的。

标签: shell

解决方案


The check indeed does not exist.

In CWRU/posix-parser/make.c, direction flags are stored (and later used in the event of an open() call in redir.c). However, in the codepaths which actually call dup2() in redir.c, the flags distinguishing between a file descriptor opened for read, write or read/write mode are never used.


推荐阅读