Pradep
Pradep

Reputation: 2024

How to get the PID of a process by giving the process name in Mac OS X ?

I am writing a script to monitor the CPU and MEM of any given process. For that i need to send in the name of the process to be monitored as a commandline argument. For example.

./monitorscript <pname>

I need to get the pid of the process in the script so that i can use a ps -p <pid> inside.

How do i get the pid of a process given its process name?

I understand that there might be multiple processes in the same name. I just want to get the first process out of that list.

Upvotes: 77

Views: 210988

Answers (9)

Fawntasia
Fawntasia

Reputation: 357

ps -o ppid=$(ps -ax | grep nameOfProcess | awk '{print $1}')

Prints out the changing process pid and then the parent PID. You can then kill the parent, or you can use that parentPID in the following command to get the name of the parent process:

ps -p parentPID -o comm=

For me the parent was 'login' :\

Upvotes: 0

Vijay C
Vijay C

Reputation: 1289

The answer above was mostly correct, just needed some tweaking for the different parameters in Mac OSX.

ps -A | grep [f]irefox | awk '{print $1}'

Upvotes: 114

bergercookie
bergercookie

Reputation: 2760

You can use the pgrep command like in the following example

$ pgrep Keychain\ Access
44186

Upvotes: 76

Ape
Ape

Reputation: 7

Why don't you run TOP and use the options to sort by other metrics, other than PID? Like, highest used PID from the CPU/MEM?

top -o cpu <---sorts all processes by CPU Usage

Upvotes: -4

hgascon
hgascon

Reputation: 821

You can install pidof with Homebrew:

brew install pidof
pidof <process_name>

Upvotes: 69

stepmuel
stepmuel

Reputation: 1218

This solution matches the process name more strictly:

ps -Ac -o pid,comm | awk '/^ *[0-9]+ Dropbox$/ {print $1}'

This solution has the following advantages:

  • it ignores command line arguments like tail -f ~/Dropbox
  • it ignores processes inside a directory like ~/Dropbox/foo.sh
  • it ignores processes with names like ~/DropboxUID.sh

Upvotes: 8

phatmann
phatmann

Reputation: 18493

This is the shortest command I could find that does the job:

ps -ax | awk '/[t]he_app_name/{print $1}'

Putting brackets around the first letter stops awk from finding the awk process itself.

Upvotes: 6

Nicholas Riley
Nicholas Riley

Reputation: 44321

Try this one:

echo "$(ps -ceo pid=,comm= | awk '/firefox/ { print $1; exit }')"

The ps command produces output like this, with the PID in the first column and the executable name (only) in the second column:

bookworm% ps -ceo pid=,comm=
    1 launchd
   10 kextd
   11 UserEventAgent
   12 mDNSResponder
   13 opendirectoryd
   14 notifyd
   15 configd

...which awk processes, printing the first column (pid) and exiting after the first match.

Upvotes: 2

chepner
chepner

Reputation: 531165

You can try this

pid=$(ps -o pid=,comm= | grep -m1 $procname | cut -d' ' -f1)

Upvotes: 1

Related Questions