Bash – How to a background process know its own PID

background-processbashprocess

I'm using bash on a RH Linux system.

Normally, you can get your own PID with the variable $$. However, if a script runs one of its own functions as a background process – that doesn't work; all functions run in the background will get the PID of the parent script when $$ is used.

For example, here is a test script:

    /tmp/test:
    #!/bin/bash
    echo "I am $$"
    function proce {
      sleep 3
      echo "$1 :: $$"
    }

    for x in aa bb cc; do
      eval "proce $x &"
      echo "Started: $!"
    done

When it is executed:

    /tmp$ ./test
    I am 5253
    Started: 5254
    Started: 5256
    Started: 5258
    /tmp$ aa :: 5253
    bb :: 5253
    cc :: 5253

So – the parent script (/tmp/test) executes as PID 5253 and fires-off three background processes with PIDs 5254, 5256 and 5258. But each of those background processes gets the value 5253 with $$.

How can these processes discover its actual PID?

Best Answer

$BASHPID may be what you are looking for.

BASHPID

Expands to the process ID of the current Bash process. This differs from $$ under certain circumstances, such as subshells that do not require Bash to be re-initialized.

As opposed to $$

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

http://www.gnu.org/software/bash/manual/bashref.html#Bash-Variables

Related Question