Most people who are familiar *nix systems use top to take a look at what’s going on in the system.
Here are just some handy commands.
- Display each CPU’s usage
top
then press shift+i
then press 1
If you have an application supporting multi-core but you see only 1 core is firing up in usage, then something is not right.
- Sort by memory
top
then press shift+m
- Batch mode
top -b -n 1 | head -n 20
This will be useful if you want to gather per-user/per-process/per-application performance metrics, which the sar
logs can’t provide. You can put this command in a simple cron job to complement logging/monitoring.
If a malicious program is running in your system, it might also try to hide from ‘top’. Let’s say the malicious user is smart enough to replace top with a tampered version to hide the malicious user/program, but forgot to hide himself in the process table, you perform a quick verification by:
> top -b -n 1 | egrep '^[[:digit:]]|^[[:space:]]' | grep -v PID | awk '{ print $1 }' | sort -n > top_pids> ps aux | grep -v PID | awk '{ print $2 }' > ps_pids> diff top_pids ps_pids
Process States
Top provides an overview of process states. Here are the meaning of each state in simple English.
- Running (R): Running, not much ambiguity.
- Waiting(S/D): Interruptible sleep (S) or uninterruptible sleep (D)
- Stopped (T): Stopped, example below
- Zombie (Z): A finished process which is still in the process table.
Stopped state
> sleep 100
Then press Ctrl + z (^Z
) to stop it (SIGSTOP). This is different from Ctrl + c which terminates the process (SIGTERM). In the stopped state, you can resume it with (SIGCONT) fg
which puts it back to the foreground (your current terminal session), or bg
which puts the process to the background.