This post is basically a follow-up to an earlier question of mine.
From the answer to that question I realized that not only I don't quite understand the whole concept of a "subshell", but more generally, I don't understand the relationship between fork
-ing and children processes.
I used to think that when process X
executes a fork
, a new process Y
is created whose parent is X
, but according to the answer to that question,
[a] subshell is not a completely new process, but a fork of the existing process.
The implication here is that a "fork" is not (or does not result in) "a completely new process."
I'm now very confused, too confused, in fact, to formulate a coherent question to directly dispel my confusion.
I can however formulate a question that may lead to enlightenment indirectly.
Since, according to zshall(1)
, $ZDOTDIR/.zshenv
gets sourced whenever a new instance of zsh
starts, then any command in $ZDOTDIR/.zshenv
that results in the creation of a "a completely new [zsh] process" would result in an infinite regress. On the other hand, including either of the following lines in a $ZDOTDIR/.zshenv
file does not result in an infinite regress:
echo $(date; printenv; echo $$) > /dev/null #1
(date; printenv; echo $$) #2
The only way I found to induce an infinite regress by the mechanism described above was to include a line like the following1 in the $ZDOTDIR/.zshenv
file:
$SHELL -c 'date; printenv; echo $$' #3
My questions are:
what difference between the commands marked
#1
,#2
above and the one marked#3
accounts from this difference in behavior?if the shells that get created in
#1
and#2
are called "subshells", what are those like the one generated by#3
called?is it possible to rationalize (and maybe generalize) the empirical/anecdotal findings described above in terms of the "theory" (for lack of a better word) of Unix processes?
The motivation for the last question is to be able to determine ahead of time (i.e. without resorting to experimentation) what commands would lead to an infinite regress if they were included in $ZDOTDIR/.zshenv
?
1 The particular sequence of commands date; printenv; echo $$
that I used in the various examples above is not too important. They happen to be commands whose output was potentially helpful towards interpreting the results of my "experiments". (I did, however, want these sequences to consist of more than one command, for the reason explained here.)
echo $$
in a subshell explicitly prints the PID of the parent shell, per POSIX. It probably isn't showing you what you wanted. Note also that zsh is well-known for aggressively optimising subshell execution, so you probably need still more care to get the effect you want.strace -o trace=process -f zsh -c ' ... '
is a good way to check your intuitions.