Understanding exec in bash

风格不统一 提交于 2019-12-10 10:45:21

问题


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)?


回答1:


Here's what exec does:

  1. Set up all redirections in the current process.
    • This is a combination of open, dup2 and close 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
  2. Replace the process image (using execve) with the specified program, if any

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) works by pipe+fork+/dev/fd/:

  1. Create a pipe as normal.
  2. Copy it to FD 63 or somewhere it won't be in the way
  3. Fork and run a program that reads/writes to the pipe.
  4. Replace the process substitution with /dev/fd/63, a special file that will return FD 63 when opened. (try echo <(ls)).

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.



来源:https://stackoverflow.com/questions/41603122/understanding-exec-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!