开发者

bash: child can not get its PID correctly

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

#!/bin/bash

foo开发者_如何学JAVA ()
{
    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


In Bash, there are $$ and $BASHPID variables that are somewhat confusing. $$ is a process ID of the script itself. $BASHPID is a process ID of the current instance of Bash. These things are not the same, but often give the same results. In your case, you used that incorrectly. Replacing $$ with $BASHPID in function foo will solve the problem.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜