help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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.

masahiro@grover:/tmp/test$ cat test.c
#include <stdio.h>
#include <unistd.h>

int main(void)
{
     printf("pid=%d, ppid=%d\n", getpid(), getppid());
}

masahiro@grover:/tmp/test$ gcc test.c
masahiro@grover:/tmp/test$
masahiro@grover:/tmp/test$ echo $$
1071740
masahiro@grover:/tmp/test$ ./a.out
pid=1073015, ppid=1071740
masahiro@grover:/tmp/test$ ( ./a.out )
pid=1073016, ppid=1071740

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.

masahiro@grover:/tmp/test$ ( ./a.out; ./a.out )
pid=1073020, ppid=1073019
pid=1073021, ppid=1073019

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/



reply via email to

[Prev in Thread] Current Thread [Next in Thread]