Re: When does bash spawn a sub-shell with ( list ) ?
From:
Chet Ramey
Subject:
Re: When does bash spawn a sub-shell with ( list ) ?
Date:
Thu, 27 Jan 2022 15:28:57 -0500
User-agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:91.0) Gecko/20100101 Thunderbird/91.4.1
On 1/27/22 2:45 PM, Masahiro Yamada wrote:
Hi,
The bash manual [1] says
"Placing a list of commands between parentheses causes
a subshell environment to be created"
In this statement, "a list of commands"
means "two commands or more",
excluding a single command.
Is this correct?
No. Bash will sometimes optimize away a child process creation (in effect,
turning `( foo )' into `(exec foo)') if it can determine that the command
has no side effects. You're seeing that here.
The shell optimized away the second fork; the command is still being
executed in a subshell environment and actions by ./a.out will not
affect its parent.
The shell couldn't optimize it away (it probably could with the last
command in the list, but it doesn't try).
The command
./a.out
and
( ./a.out )
printed the same ppid, 1071740.
So, ( ./a.out ) did not fork a new subshell.
It did. Then it ran ./a.out in that subshell without forking again.
Why do you need the shell to fork twice?
--
``The lyf so short, the craft so long to lerne.'' - Chaucer
``Ars longa, vita brevis'' - Hippocrates
Chet Ramey, UTech, CWRU chet@case.edu http://tiswww.cwru.edu/~chet/