Linux – bash: child failed to get its PID correctly

bash: child failed to get its PID correctly… here is a solution to the problem.

bash: child failed to get its PID correctly

Why do both parent and child think they have the same pid when I run the script below?

#!/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

Solution

In Bash, there are some $$ and $BASHPID variables, which are confusing. $$ is the process ID of the script itself. $BASHPID is the process ID 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 $BASHPID in the function foo solves the problem.

See also Internal Variables section Bash Advanced Scripting Guide for more details.

Related Problems and Solutions