[cs631apue] Does $$ represents the shell's pid or the current process's pid?

Jan Schaumann jschauma at stevens.edu
Thu Dec 17 22:10:02 EST 2015


Shicong Huang <shuang14 at stevens.edu> wrote:
 
> The instruction said "$$ The current process ID.". But it seems bash always
> treats $$ as the process id of itself.

Both is correct: '$$' is expanded to the current process ID at the time
the shell parses the command.  At that point in time, the current
process ID is the pid of the shell.  That is, if your current pid is
1234, then running

whatever | echo $$

expands to

whatever | echo 1234

and the shell then forks processes for 'whatever' and 'echo 1234'.

If you created a new process before the shell expands the command, then
you'd end up with a different pid there:

$ echo $$
8286
$ echo | /bin/sh -c 'echo $$'
8310
$ 

Here, the single quotes prevent the expansion of $$ on the command-line,
and "/bin/sh -c 'echo $$'" will be a new process with pid 8310.

Your shell doesn't handle either single- or double-quoting arguments, so
you should perform parameter expansion prior to forking any new
processes.

-Jan


More information about the cs631apue mailing list