Linux – How to Get Number of Processes Waiting for CPU

cpucpu usage

If CPU is running 100% usage, other processes should be put inside a run queue. Which command can I use to get the size of the run-queue? vmstat seems to return a related value of the CPU like below:

procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
 0  0      0 875128 576328 2147136    0    0     1     4    3   11  0  0 99  0  0

According to the manual, "r: The number of runnable processes (running or waiting for run time).", the column r indicates the number of processes including both running and wait processes. How can I just get the number the waiting processes?

Best Answer

The number of runnable processes is given by procs_running in /proc/stat:

awk '/procs_running/ { print $2 }' /proc/stat

Subtract the number of CPU threads available, stopping at 0, and you’ll get the number of scheduling units (processes or threads) waiting to be scheduled. You can determine the number of CPU threads available from /proc/stat too, using the cpu? lines. Overall:

awk '/cpu[^ ]/ { nb = substr($1, 4); if (nb > nbcpus) nbcpus = nb };
/procs_running/ { runqueue = $2 - nbcpus; if (runqueue < 0) runqueue = 0; print runqueue }' /proc/stat
Related Question