gpt4 book ai didi

linux - () 构造总是会启动一个子 shell 吗?

转载 作者:IT王子 更新时间:2023-10-29 00:50:30 26 4
gpt4 key购买 nike

当前 shell 是

$ echo $$
23173

注意 ps 的父级是当前 shell

$ ( ps -o pid,ppid,cmd )
PID PPID CMD
8952 23173 ps -o pid,ppid,cmd
23173 23169 bash

但是在这里,ps 的父级是子 shell (bash)

$ ( echo hello ; ps -o pid,ppid,cmd )
hello
PID PPID CMD
8953 23173 bash
8954 8953 ps -o pid,ppid,cmd
23173 23169 bash

bash 正在做优化吗?为什么额外的 echo 会产生差异并在第三种情况下产生子 shell ?

最佳答案

是的,您看到的是优化。从技术上讲,根据定义,(…) 结构总是启动一个子 shell。大多数时候,子 shell 在单独的子进程中运行。这确保了在子 shell 中完成的所有操作都保留在子 shell 中。如果 bash 可以保证这个隔离属性,它就可以自由地使用它喜欢的任何实现技术。

在片段 ( ps -o pid,ppid,cmd ) 中,很明显没有任何东西可以影响父 shell,所以 bash 中有一个优化使得它不会为子 shell 。片段 ( echo hello ; ps -o pid,ppid,cmd ) 太复杂了,优化器无法识别不需要子 shell。

如果您尝试使用 ksh,您会注意到它的优化器更积极。例如,它也不会为 ( echo hello ; ps -o pid,ppid,cmd ) 派生子进程。

关于linux - () 构造总是会启动一个子 shell 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5928590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com