Why is $$ returning the same id as the parent process?

ruanhao picture ruanhao · Jan 11, 2014 · Viewed 295.1k times · Source

I have problem with Bash, and I don't know why.
Under shell, I enter:

echo $$    ## print 2433
(echo $$)  ## also print 2433
(./getpid) ## print 2602

"getpid" is a C program to get current pid, like:

   int main() {
    printf("%d", (int)getpid());
    return 0;
   }

What confuses me is that:

  1. I think "(command)" is a sub-process (am i right?), and i think its pid should be different with its parent pid, but they are the same, why...
  2. when i use my program to show pid between parenthesis, the pid it shows is different, is it right?
  3. is '$$' something like macro?

Can you help me?

Answer

chepner picture chepner · Jan 11, 2014

$$ is defined to return the process ID of the parent in a subshell; from the man page under "Special Parameters":

$ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell.

In bash 4, you can get the process ID of the child with BASHPID.

~ $ echo $$
17601
~ $ ( echo $$; echo $BASHPID )
17601
17634