Get pid of current subshell

Viewed 20634

I am trying to get the pid of a currently executing subshell - but $$ is only returning the parent pid:

#!/usr/bin/sh

x() {
  echo "I am a subshell x echo 1 and my pid is $$"
}

y() {
  echo "I am a subshell y echo 1 and my pid is $$"
}


echo "I am the parent shell and my pid is $$"
x &
echo "Just launched x and the pid is $! "

y &
echo "Just launched y and the pid is $! "

wait

Output

I am the parent shell and my pid is 3107
Just launched x and the pid is 3108
I am a subshell x echo 1 and my pid is 3107
Just launched y and the pid is 3109
I am a subshell y echo 1 and my pid is 3107

As you can see above, when I run $$ from the function that I've backgrounded, it does not display the PID as when I do $! from the parent shell.

6 Answers

If you use Linux-kernel, you can use Linux-kernel's /proc/self feature to do this:

In simplest form: cd -P /proc/self && basename "${PWD}"

To keep the PWD and OLDPWD variable: PWD_BACKUP="${PWD}";OLDPWD_BACKUP="${OLDPWD}";cd -P /proc/self && basename "${PWD}";cd "${PWD_BACKUP}";OLDPWD="${OLDPWD_BACKUP}"

For example:

$ cd -P /proc/self && basename "${PWD}"
26758
$ (cd -P /proc/self && basename "${PWD}")
26959
$ (cd -P /proc/self && basename "${PWD}")
26961
$ 

@John1024 's answer is great, but there's a little problem in there.

when a command run like (...), the command will run in a new subprocess, so

( : ; bash -c 'echo $PPID' ) 

will return process_id of (...), not the function's process id that call (...)

if you want the function's process_id, you can just run:

$SHELL -c 'echo $PPID'

and the process_id will be outputed to stderr

if you want get the function's process_id form a variable, you can run:

$SHELL -c 'echo $PPID' | read -s func_pid

then you can get the pid from variable ${func_pid}

note: don't run this command in (...), otherwise it'll return the process_id of (...)

Related