0

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"?

Zoltan K.
  • 493
  • I don't quite understand the question here. What is it you are asking? How are you trying to use $$? – terdon Oct 05 '21 at 12:54
  • Yes, foo & runs foo 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
  • @terdon The question is, is there any official documentation that explains how $$ will be expanded in a backgrounded process? – Zoltan K. Oct 05 '21 at 21:37
  • @Gilles'SO-stopbeingevil' Could you point me to where this is stated? I went through the other questions, and the referenced documentation, but I could not find this part. The concept of subshell always seemed to be connected with the (...) 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
  • https://unix.stackexchange.com/questions/421020/what-is-the-exact-difference-between-a-subshell-and-a-child-process, especially the accepted answer. (…) 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

0 Answers0