How can I get the pid of a subshell?
For example:
$ echo $$ 16808
This doesn’t work, because the original shell expands $$:
$ ( echo $$ ) 16808
Why does single quoting not work? After the original shell removes the single quote, does the subshell not expand $$ in itself?
$ ( echo '$$' ) $$
Why does eval not work either? Is eval run by the subshell? Why does it give me the original shell’s PID?
$ ( eval echo '$$' ) 16808
Thanks.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
$ echo $BASHPID 37152 $ ( echo $BASHPID ) 18633
From the manual:
BASHPIDExpands 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.
$Expands to the process ID of the shell. In a
()subshell, it
expands to the process ID of the current shell, not the
subshell.
Related:
- Do parentheses really put the command in a subshell?, especially parts of Gilles’ answer.
Method 2
In addition to bash‘s $BASHPID, you can do it portably with:
pid=$(exec sh -c 'echo "$PPID"')
Example:
(pid=$(exec sh -c 'echo "$PPID"'); echo "$$ $pid")
You can make it into a function:
# usage getpid [varname]
getpid(){
pid=$(exec sh -c 'echo "$PPID"')
test "$1" && eval "$1=$pid"
}
Notice that some shells (eg. zsh or ksh93) do NOT start a subprocess for each subshell created with (...); in that case, $pid may be end up being the same as $$, which is just right, because that’s the PID of the process getpid was called from.
Method 3
On Linux a cross-shell solution (at least dash, bash, zsh) which does not spawn a new process is
read -r this_pid < /proc/self/stat; echo ${this_pid%% *}
At least in bash and zsh we can also use space as read-delimeter:
read -d ' ' this_pid < /proc/self/stat ; echo $this_pid
See also man 5 proc section /proc/[pid]/stat
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0