14

Is it possible to get a file name of a process using PID? ps displays a lot of useful information about a process, but not a hint about a process executable file location.

5 Answers 5

17

One way of getting the process's binary location is to use lsof and grep for the first txt segment. For example, in the shell to see what binary the shell is, use the shell's PID in place of $$.

$ lsof -p $$ | grep txt
bash    78228 blair  txt    REG   14,2   1244928   6568359 /bin/bash
bash    78228 blair  txt    REG   14,2   1059792  23699809 /usr/lib/dyld
bash    78228 blair  txt    REG   14,2 136368128  81751398 /private/var/db/dyld/dyld_shared_cache_i386

You can see that the shell is using /bin/bash.

This technique works if the process was launched using an absolute or relative path. For example, going into one shell and running

$ sleep 1234567

and using ps in another shell only shows how it was launched:

$ ps auxww|grep '[s]leep'
blair    79462   0.0  0.0   600908    744 s011  S+   11:17PM   0:00.00 sleep 1234567

using lsof shows which binary it ran:

$ lsof -p 79462 | awk '$4 == "txt" { print $9 }'
/opt/local-development/bin/gsleep

I have MacPorts coreutils +with_default_names installed, which explains that I picked up gsleep and not /bin/sleep.

1
  • Piping lsof output through awk works great, with one minor addition. I added ; exit after the print statement so that only the first txt entry will be printed even if there are several as in the bash example.
    – qqx
    Nov 12, 2015 at 20:59
3

ps -ef with grep works for me. For a specific file name, simply pipe through grep thus:

MacBook:~ Me$ ps -ef | grep Safari | grep -v grep
  501 15733   301   0   0:25.76 ??         1:58.24 /Applications/Safari.app/Contents/MacOS/Safari -psn_0_4977855

(That final 'grep -v grep' simply stops you getting your own grep command in the output)

1
  • This worked in my case instead of lsof -p $PID, which was not returning any output for a PID associated with httpd. Jan 1, 2022 at 17:23
2

Example: you're after the associate process command name for PID 45109...

>    % ps awx | awk '$1 == 45109 { print $5 }'
>    /Applications/Safari.app/Contents/MacOS/Safari
2
  • 2
    Will not show full binary path if binary was started just by name without specifying path.
    – grigoryvp
    May 28, 2009 at 8:56
  • doesn't work right, if path contains whitespace Oct 28, 2019 at 9:27
2

ps -p <pid> -Ocommand

L1A1:~ a1155344$ ps -p1 -Ocommand
  PID   TT  STAT      TIME COMMAND
    1   ??  Ss     0:02.26 /sbin/launchd
1

try ps aux

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .