Will () construct always launch a subshell?

Current shell

$ echo $$ 23173 

Note that the parent element ps is the current shell

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

But here the parent element ps is a subshell (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 

Is bash optimized? Why did an additional echo affect the difference and give rise to a subshell in the 3rd case?

+6
source share
2 answers

Yes, what you see is optimization. Technically, a design (…) always launches a subshell by definition. In most cases, the subshell works in a separate subprocess. This ensures that everything that is done in the subshell remains in the subshell. If bash can guarantee this isolation property, he can use any implementation technique that he likes.

In the fragment ( ps -o pid,ppid,cmd ) it is obvious that nothing can influence the parent shell, therefore there is optimization in bash, which makes it not fork as a separate process for the subshell. The fragment ( echo hello ; ps -o pid,ppid,cmd ) too complex for the optimizer to recognize that no subshell is required.

If you are experimenting with ksh , you will notice that its optimizer is more aggressive. For example, it does not support a subprocess for ( echo hello ; ps -o pid,ppid,cmd ) .

+6
source

A subhellea, consisting of one simple command instead of a list or pipeline of more than one command, can be implemented simply by β€œexecuting” the command, i.e. replacing a subshell with a process for the called command. If the subshell is more complex, then a simple exec is not possible; the subshell must remain around to control the sequence of commands.

From your diagnostics, it is impossible to tell the difference between bash optimizations, where a subshell consisting of a simple command is optimized for the "direct" fork and exec of the called command or subshell fork, followed by the exec of the called command. This is not surprising, since the difference (almost?) Is completely academic.

+1
source

Source: https://habr.com/ru/post/887564/


All Articles