How to find the process id for the app instance created by "open" command
When I programmerly do open -F -W -n -g -a /Applications/Safari.app/Contents/MacOS/Safari https://kernel.org
, I got back the process of open
and its pid 93930.
But that's not the process (93931) of newly created Safari instance itself.
huocp 93931 0.0 1.9 6047904 160240 ?? S 11:55am 0:04.39 /Applications/Safari.app/Contents/MacOS/Safari
huocp 93930 0.0 0.1 4340272 12212 s004 S+ 11:55am 0:00.07 open -F -W -n -g -a /Applications/Safari.app/Contents/MacOS/Safari https://kernel.org
Now I have no way to close the Safari process programmerly. I can close the open
process programmerly by killing 93930, but it leaves 93931 running.
So the question is: is there a way to get the pid of the application instance created by open
command?
93931 (safari) is not even a child process of 93930 (open), I tried with pstree command.
Similar question on StackOverflow
If you're programmatically doing this, one way to get the opened app's pid (subsequently using it to kill the process) is to get the grep the output of ps
aux
passing it the application's name.
ps aux | grep -v grep | grep -I <AppName> | sort -rn | head -1 | awk '{print $2}'
Basically, pipe the output of the ps aux
command through grep and sort it based on the value of the start time column.
As pointed by @user3439894 below, there's an easier way without the above rigmarole.
pgrep -nx Safari
returns the PID of the last opened instance of Safari and
pkill -nx Safari
kills the last opened instance of Safari.