Jse*_*mol 3 file-descriptors fork
当我们fork()
一个进程时,子进程继承了文件描述符。问题是,为什么?
正如我所看到的,当每个进程都试图跟踪 r/w 指针的位置时,共享文件描述符是一件令人头疼的事情。
为什么做出这个设计决定?
考虑一个shell片段
{ somecmd; othercommand *.txt; } > outputfile
Run Code Online (Sandbox Code Playgroud)
shell 打开outputfile
一次,在开始重定向时,然后将文件句柄传递给somecmd
and othercmd
,处理它fork
关闭。给定分组,用户可能没有错误地期望两个命令的输出都以 结束outputfile
,就像它们最终出现在屏幕上一样。(如果该{ }
组是一个 shell 脚本,那将是相同的。)
如果文件位置对于所有进程都是独立的,则 from 的输出othercommand
将破坏somecmd
. 如果fork
重置文件句柄上的位置,shell 将无法传递othercommand
指向结尾的句柄outputfile
(就像在 之后一样somecmd
)。我们必须使用管道来收集两个命令的输出(无论如何它们都是位置不可知的),并让另一个程序连接这两个命令的输出:
{ somecmd; othercommand *.txt } | cat > outputfile
Run Code Online (Sandbox Code Playgroud)