Use ps to view Processes, sort them, and kill them

This is a quick note on how to work with linux/Unix/Mac processes.

If you want to go straight for the ‘kill’

Start by getting the process ID with pgrep process name. Then use kill to kill the process. But, be nice about it, ok?

$>pgrep mongod
$>kill <PID>

Use ps to List Processes

$> ps
PID TTY TIME CMD
13707 ttys000 0:00.03 -bash
12192 ttys002 0:00.08 -bash

The ps command without any options is not very useful.

NOTE: Mac users may want to refer to this link for some differences in the flags used.

Display ‘all‘ processes with the ‘a‘ option. The ‘x‘ (e on Mac OS) options instructs ps to show current processes even if it is not associated with the terminal or TTY.
————————————–
(NOTE: replace x with e for mac users)
————————————–
$> ps -ax

Pipe the output to the less command to make it easier to read.

$> ps -ax | less

Processes may be filtered by user as follows.

$> ps -u userguy

Processes may be filtered by ‘cpu’ usage in ascending order with the –sort option using -pcpu.

$> ps -aux –sort -pcpu | less

On Mac OS
r  Sort by current CPU usage, instead of the combination of controlling terminal and process ID.

Processes may be filtered by ‘mem’ory utilization in ascending order with the –sort option using -pmem.

ps -em

On MAC
m Sort by memory usage, instead of the combination of controlling terminal and process ID.

On Linux
Putting it all together you can can get the top5 results as follows.

$> ps -aux –sort -pcpu,+pmem | head -n 5

By the way, here is another excellent ps reference link with examples I found useful.

This post is just notes at this point. Feel free to comment and correct any errors you find.

Leave a Reply

Your email address will not be published.