How do I count specific processes on Mac OS X?
-
13-11-2019 - |
문제
Using a Mac, what would be the best way to count the number of instances of a particular process I am running? This is for a script I am writing to find the number of ffmpeg
processes running on my machine.
Should I be using top
here? ps aux|grep ffmpeg
? What would be the best way to get the number?
해결책
grep -c will count occurrences:
count=`ps aux | grep -v "grep" | grep -c ffmpeg`
echo $count
다른 팁
ps aux | grep ffmpeg | wc -l
will get you the number of processes that mention the phrase 'ffmpeg' you'll need to minus 1 on this value as ps aux | grep ffmpg
is a process also.
You're looking for the program called "wc" -- "wc -l" will count lines for you.
"man wc" for details.
You can try the killall command on the Mac:
$ killall -s ffmpg
kill -TERM 20148
kill -TERM 20146
kill -TERM 20140
The -s
means just list what you'd do, but don't actually kill any processes. Pipe it to wc
, and you should get your result:
$ killall -s ffmpg | wc -l
3
In a shell script, you can do something like this:
num_of_processes=$(killall -s ffmpg | wc -l)
$ pgrep -c ffmpeg
If you don't use pgrep
then mere grep
might produce false positives.
To avoid it you could try -C
option:
$ ps -C ffmpeg -o pid= | wc -l
Check that your ps
version interprets it correctly.