How can I count the number of sleeping processes in my system?

Extended explanation... trusting you to take it all in since it's your homework...

List processes with the ps command

$ ps
  PID TTY          TIME CMD
 4879 pts/3    00:00:00 bash
 5003 pts/3    00:00:00 ps

Oh, this only shows the processes of the current session. We want to show all processes in the system. For that we can use the -e flag

$ ps -e
  PID TTY          TIME CMD
    1 ?        00:00:05 systemd
    2 ?        00:00:00 kthreadd
    3 ?        00:00:00 ksoftirqd/0
[and many more lines]

but how do we show which ones are sleeping??

You can use the -l option or u option. This gives more detail including the state of the process. Sleeping processes have a letter S or D in the STAT column

from man ps

PROCESS STATE CODES Here are the different values that the s, stat and state output specifiers (header "STAT" or "S") will display to describe the state of a process:

           D    uninterruptible sleep (usually IO)
           R    running or runnable (on run queue)
           S    interruptible sleep (waiting for an event to complete)
           T    stopped by job control signal
           t    stopped by debugger during the tracing
           W    paging (not valid since the 2.6.xx kernel)
           X    dead (should never be seen)
           Z    defunct ("zombie") process, terminated but not reaped by its parent

We can format the ps output to show ONLY the states, to make it easier to count them:

ps -e -o state

here we use -e to get all the processes and the -o flag, followed by the type of output we want. This command outputs only the state letter. We can then pipe (using |) this output to grep to count the lines with S or D, the sleeping processes:

ps -e -o state | grep -cE 'S|D'

grep searches for text. The -c option tells it to only count matches instead of outputting the found text itself. The -E option tells grep to use extended regex, so that we can use the | characters to match thing OR stuff using the expression: thing|stuff. When using regex, use single quotes to prevent expansions by the shell.


Very easy if you know that ps command outputs status for sleeping processes as either S for interruptible sleep and D for uninterruptible sleep, and you can use -o s flag to find the state of those. Now all you have to do is to run output through grep that will count occurrences of those flags. Like so:

$ ps -e -o s | grep -o 'S\|D' -c                                                                                         
260