问题描述
阅读>如何执行Builtin在bash中工作,我知道它的基本功能是在不进行分叉的情况下替换当前进程.它似乎还用于在当前进程中重定向I/O和关闭文件描述符,这使我感到困惑.这是exec
的一些无关的附加功能吗?在替换当前过程"的上下文中可以理解吗?以及与流程替代(例如, exec 3< <(my program)
?
After reading explanations of how the exec builtin works in bash, I understand that its basic function is to replace the current process without forking. It also seems to be used for redirecting I/O and closing file descriptors in the current process, which confuses me. Is this some unrelated additional thing exec
does? Can it be understood in the context of "replacing the current process"? And how does this work when combined with process substitution, e.g. exec 3< <(my program)
?
推荐答案
这是exec
的作用:
- 设置当前进程中的所有重定向.
- 对于大多数操作,例如
> foo
,这是 -
pipe
+fork
+/dev/fd/*
用于替换进程 - 已为here-documents和here-strings创建并打开了临时文件
open
,dup2
和close
系统调用的组合 - 对于大多数操作,例如
- Set up all redirections in the current process.
- This is a combination of
open
,dup2
andclose
syscalls for most operations like> foo
pipe
+fork
+/dev/fd/*
is used for process substition- Temporary files are created and opened for here-documents and here-strings
- This is a combination of
如果您未指定要运行的程序,则仅跳过步骤2,因此所有重定向都会影响脚本的其余部分.
If you don't specify a program to run, step 2 is simply skipped, and all redirections therefore affect the rest of the script.
<(Process substitution)
通过pipe
+ fork
+ /dev/fd/
起作用:
<(Process substitution)
works by pipe
+fork
+/dev/fd/
:
- 正常创建管道.
- 将其复制到FD 63或不会妨碍的地方
- 分叉并运行一个程序,该程序可读取/写入管道.
- 用
/dev/fd/63
替换过程替换,这是一个特殊文件,打开后将返回FD 63. (尝试echo <(ls)
).
- Create a pipe as normal.
- Copy it to FD 63 or somewhere it won't be in the way
- Fork and run a program that reads/writes to the pipe.
- Replace the process substitution with
/dev/fd/63
, a special file that will return FD 63 when opened. (tryecho <(ls)
).
从那时起,它的工作原理与从任何其他文件重定向一样.打开/dev/fd/63
以便在FD 3上进行读取,然后最终从管道读取数据. exec
因此不需要做任何特别的事情.
From then on, it works just like redirecting from any other file. You open /dev/fd/63
for reading on FD 3, and then you end up reading from the pipe. exec
therefore doesn't need to do anything special.
这篇关于了解bash中的exec的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!