Linux proc/pid/fd for stdout是11?

ste*_*heg 6 linux file-descriptor sh

执行stdout重定向到文件的脚本.所以/ proc/$$/fd/1应指向该文件(因为stdout fileno为1).但是,文件的实际fd是11.请解释,为什么.

这是会议:

$ cat hello.sh
#!/bin/sh -e
ls -l /proc/$$/fd >&2

$ ./hello.sh > /tmp/1
total 0
lrwx------ 1 nga users 64 May 28 22:05 0 -> /dev/pts/0
lrwx------ 1 nga users 64 May 28 22:05 1 -> /dev/pts/0
lr-x------ 1 nga users 64 May 28 22:05 10 -> /home/me/hello.sh
l-wx------ 1 nga users 64 May 28 22:05 11 -> /tmp/1
lrwx------ 1 nga users 64 May 28 22:05 2 -> /dev/pts/0
Run Code Online (Sandbox Code Playgroud)

Yan*_*ier 5

我怀疑,但这在很大程度上取决于你的shell的行为方式.您看到的文件描述符是:

  • 0:标准输入
  • 1:标准输出
  • 2:标准错误
  • 10:运行脚本
  • 11:脚本正常标准输出的备份副本

描述符10和11在exec上是关闭的,因此在该ls过程中不会出现.然而,分叉之前为 0s 准备了0-2 .我在破折号(Debian Almquist shell)中看到了这种行为,但在bash(Bourne再次shell)中却没有.Bash反而在分叉后执行文件描述符操作,并且顺便使用255而不是10用于脚本.在分叉后执行更改意味着它不必恢复父级中的描述符,因此它没有备份副本到dup2.