Bash: the child cannot correctly receive his PID code

why is it that when I run the script below, both the parent and the child think that they have the same pid?

#!/bin/bash

foo ()
{
    while true
    do
        sleep 5
        echo child: I am $$
    done
}


( foo ) &

echo parent: I am $$ and child is $!

>./test.sh
parent: I am 26542 and child is 26543
>child: I am 26542
child: I am 26542
+3
source share
1 answer

Bash has $$and variables $BASHPIDthat are somewhat confusing. $$is the process id of the script itself. $BASHPIDis the process identifier of the current Bash instance. These things are not the same, but often give the same results. In your case, you used it incorrectly. Replacing $$with $BASHPIDin functions foowill solve the problem.

See Bash Internal Variables Advanced Scripting Guide for more details.

+4
source

All Articles