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.
Run the command lsof -i : (make sure to insert your port number) to find out what is running on this port. Copy the Process ID (PID) from the Terminal output.
In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column. Click on any column name to sort. You can right click a process name to see more options for a process.
To find the process that is listening to a port on Mac OS X, we'll use the lsof command to find the process ID (PID), and the ps command to show the name.
Launch Terminal (Finder > Applications > Utilities). When Terminal is running, type top and hit Return. This will pull up a list of all your currently running processes. As in the Activity Monitor, this list shows your processes in decreasing order of how much of your resources they're consuming.
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}'
You can use the pgrep command like in the following example
$ pgrep Keychain\ Access
44186
You can install pidof
with Homebrew:
brew install pidof
pidof <process_name>
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:
tail -f ~/Dropbox
~/Dropbox/foo.sh
~/DropboxUID.sh
You can try this
pid=$(ps -o pid=,comm= | grep -m1 $procname | cut -d' ' -f1)
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.
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.
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