I know in bash we can create subshells using round parenthesis (
and )
. As per bash man page:
(list) list is executed in a subshell environment
Also to get the current process id we use:
echo $$
Now my question is how to get process id of a subshell created using (
and )
on command line?
If I use this:
echo $$; ( echo $$; )
I will get the parent shell's process id printed twice on stdout since $$
gets expanded even before subshell is created. So how to really force the lazy expansion?
[Solution should work on Mac as well not just Linux]
Suggested linked answer doesn't work since echo $BASHPID
does not work on my Mac and returns blank.
You can run ps -A in the terminal to show all the processes (with their process ID) that are currently running.
There is a solution that can get the PID of sub_process1: Enumerate all processes with the command ps aux ; Get PPID(parent process ID) for each process with the command ps -f [PID] . If the PPID is equal to the PID of process1, the process must be sub_process1.
Press Ctrl+Shift+Esc on the keyboard. Go to the Processes tab. Right-click the header of the table and select PID in the context menu.
Thanks to all of you for spending your valuable time in finding answer to my question here.
However I am now answering my own question since I've found a hack way to get this pid on bash ver < 4 (will work on all the versions though). Here is the command:
echo $$; ( F='/tmp/myps'; [ ! -f $F ] && echo 'echo $PPID' > $F; )
It prints:
5642 13715
Where 13715 is the pid of the subshell. To test this when I do:
echo $$; ( F='/tmp/myps'; [ ! -f $F ] && echo 'echo $PPID' > $F; bash $F; ps; )
I get this:
5642 13773 PID TT STAT TIME COMMAND 5642 s001 S 0:02.07 -bash 13773 s001 S+ 0:00.00 -bash
Telling me that 13773 is indeed the pid of the subshell.
Note: I reverted back to my original solution since as @ChrisDodd commented that echo $$; ( bash -c 'echo $PPID'; )
doesn't work Linux. Above solution of mine works both on Mac and Linux.
Unfortunately there's no easy way to do this prior to bash version 4, when $BASHPID was introduced. One thing you can do is to write a tiny program that prints its parent PID:
int main() { printf("%d\n", getppid()); return 0; }
If you compile that as ppid
and put it in your path, you can call it, eg:
$ (echo $$; ppid) 2139 29519 $ (x=$(ppid); echo $x) 29521
One oddness I noticed, however, is that if you write
$ (ppid)
it doesn't seem to actually run it in a subshell -- you need at least two commands inside the parentheses for bash to actually run them in a subshell.
You can do :
$ ( your_action ) &
[1] 44012
And find subprocess' PID like that :
$ echo "The sub PID : $!"
The Sub PID : 44012
$!
returns the last job in background's PID. (see this manual)
Use homebrew to install pgrep on the Mac: brew install pgrep
Check out Link to install Homebrew.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With