了解bash中的exec [英] Understanding exec in bash

查看:126
本文介绍了了解bash中的exec的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读>如何执行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的作用:

  1. 设置当前进程中的所有重定向.
    • 对于大多数操作,例如> foo
    • ,这是opendup2close系统调用的组合
    • pipe + fork + /dev/fd/*用于替换进程
    • 已为here-documents和here-strings创建并打开了临时文件
  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,因此所有重定向都会影响脚本的其余部分.

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/:

  1. 正常创建管道.
  2. 将其复制到FD 63或不会妨碍的地方
  3. 分叉并运行一个程序,该程序可读取/写入管道.
  4. /dev/fd/63替换过程替换,这是一个特殊文件,打开后将返回FD 63. (尝试echo <(ls)).
  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)).

从那时起,它的工作原理与从任何其他文件重定向一样.打开/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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆