According to the man, $$
:
Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell.
I did some testing:
$ echo $$
20823
$ echo $$ &
[1] 6152
20823
$ ( echo $$ )
20823
[1]+ Done echo $$
$ ( echo $$ ) &
[1] 10092
$ 20823
[1]+ Done ( echo $$ )
$ f() { echo f: $$ ; }
$ f
f: 20823
$ f &
[1] 5674
$ f: 20823
[1]+ Done f
$ ( f ) &
[1] 7219
f: 20823
$ ( f )
f: 20823
[1]+ Done ( f )
Is it safe to assume that a backgrounded process counts as a subshell, for the purpose of $$
? Is this reliable, or just a coincidence?
Instead of relying on $$
, I could just save the PID in a var in the main process, and pass it around. But it seems, this is what already is happening with $$
, be it (...)
or &
, or any variation of these.
The following questions-and-answers shed some light, but not conclusive enough for the backgrounded-process vs $$
issue:
How can I get the pid of a subshell?
Do parentheses really put the command in a subshell?
What is the exact difference between a "subshell" and a "child process"?
$$
? – terdon Oct 05 '21 at 12:54foo &
runsfoo
in a subshell. That's already covered in the duplicate question. It is a subshell, so it counts as a subshell for the purpose of$$
as well as for every other purpose. – Gilles 'SO- stop being evil' Oct 05 '21 at 12:59$$
will be expanded in a backgrounded process? – Zoltan K. Oct 05 '21 at 21:37(...)
notation. I would like to find some authoritative source that this is not just an implementation quirk, but something to be relied upon longterm. – Zoltan K. Oct 05 '21 at 21:51(…)
is just one way among many to create a subshell. It's the way that does nothing but create a subshell. Many other constructs have a main effect, plus a complementary effect a creating a subshell, for example&
puts the left-hand side in the background, and to achieve that it puts it in a subshell. – Gilles 'SO- stop being evil' Oct 06 '21 at 07:26