How to get subshell's PID in Korn Shell (equivalent of $BASHPID)
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')
You can achieve what you want, but you need to put run_something into a separate script. I'm not exactly sure why, but $$ is not re-evaluated when it is used in a function in the same script that is calling it. I guess that the value of $$ is assigned once after the script is parsed and before it is executed.
run_in_background.sh
#
echo "PID at start: $$"
function run_in_background {
echo "PID in run_in_background $$"
./run_something.sh &
echo "PID of backgrounded run_something: $!"
}
run_in_background
echo "PID of run in background $!"
run_something.sh
#
echo "*** PID in run_something: $$"
sleep 10;
output
PID at start: 24395
PID in run_in_background 24395
PID of backgrounded run_something: 24396
PID of run in background 24396
*** PID in run_something: 24396