Korn Shell – How to Get Subshell’s PID Equivalent to $BASHPID

kshshellshell-scriptsubshell

In bash you have this handy variable: $BASHPID wich always returns the currently running subshell's PID. How can I get a subshell's PID in ksh? For example see the code below:

#!/usr/bin/ksh93

echo "PID at start: $$"

function run_in_background {
  echo "PID in run_in_background $$"
  run_something &
  echo "PID of backgrounded run_something: $!"
}

function run_something {
  echo "*** PID in run_something: $$"
  sleep 10;
}    

run_in_background
echo "PID of run in background $!"

This outputs the following:

PID at start: 5328
PID in run_in_background 5328
*** PID in run_something: 5328
PID of backgrounded run_something: 5329
PID of run in background 5329

What I want is the line starting with **** to output the subshell's PID, in the example's case that would be 5329.

Best Answer

I don't think that's available in ksh. There's a POSIX solution which involves running an external process:

sh -c 'echo $PPID'

On Linux, readlink /proc/self would also work, but I fail to see any advantage (it might be marginally faster; it could be useful on a BusyBox variant that has readlink but not $PPID, but I don't think there is one).

Note that in order to get the value in the shell, you need to be careful not to run that command in a short-lived sub-sub-shell. For example, p=$(sh -c 'echo $PPID') might show the output of the subshell that invokes sh within the command substitution (or it might not, some shells optimize that case). Instead, run

p=$(exec sh -c 'echo $PPID')
Related Question