gpt4 book ai didi

shell - 管道是否保证在任何 POSIX shell 中创建子 shell?

转载 作者:行者123 更新时间:2023-12-01 03:33:05 29 4
gpt4 key购买 nike

此 shell 脚本按预期运行。

trap 'echo exit' EXIT

foo()
{
exit
}

echo begin
foo
echo end

这是输出。
$ sh foo.sh
begin
exit

这表明脚本在执行 foo 时退出.

现在看下面的脚本。
trap 'echo exit' EXIT

foo()
{
exit
}

echo begin
foo | cat
echo end

这里唯一的区别是 foo 的输出正在通过管道传输到`cat.现在输出如下所示。
begin
end
exit

这表明脚本在执行 foo 时没有退出因为 end被打印。

我相信这是因为在 bash 中,管道会导致打开子 shell ,所以 foo | cat相当于 (foo) | cat .

在任何 POSIX shell 中都保证这种行为吗?我在 http://pubs.opengroup.org/onlinepubs/9699919799/ 的 POSIX 标准中找不到任何内容这意味着管道必须通向子 shell 。有人可以确认这种行为是否可以依赖吗?

最佳答案

2.12 Shell Execution Environment你找到这句话:

A subshell environment shall be created as a duplicate of the shell environment, except that signal traps that are not being ignored shall be set to the default action. Changes made to the subshell environment shall not affect the shell environment. Command substitution, commands that are grouped with parentheses, and asynchronous lists shall be executed in a subshell environment. Additionally, each command of a multi-command pipeline is in a subshell environment; as an extension, however, any or all commands in a pipeline may be executed in the current environment. All other commands shall be executed in the current shell environment.



这个问题的关键句子在哪里

Additionally, each command of a multi-command pipeline is in a subshell environment; as an extension, however, any or all commands in a pipeline may be executed in the current environment



因此,如果没有扩展名( bash 用于诸如 lastpipe 之类的东西,我认为也用于管道中的第一个元素,但显然不是或至少不总是),看起来您可以假设会有一个子shell对于管道的每个部分,但异常(exception)意味着您不能完全指望这一点。

关于shell - 管道是否保证在任何 POSIX shell 中创建子 shell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36768286/

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