top displays these numbers in its summary:

Tasks: 193 total, 1 running, 192 sleeping, 0 stopped, 0 zombie

I'm looking for a way to get them some other way -- running a program, parsing a /proc file.

Do you know of a way to get those numbers?

The closest I've been able to get is:

pgrep "" -c

and top & pgrep:

top -b -n 1 | head -n 2 | tail -n 1; pgrep "" -c

never agree ...

e.g. 194 vs 191

grep 'procs' /proc/stat
procs_running 2
procs_blocked 0

And a mention of running, sleeping, stopped, zombie here: http://procps.cvs.sourceforge.net/viewvc/procps/procps/top.c?revision=1.134&view=markup#l1025

This grep turned up a match, sleeping is 192:

 grep -R sleeping /proc/*/status | wc -l

but its way of doing sleeping and pgrep's way of doing total don't add up:

top -b -n 1 | head -n 2 | tail -n 1; pgrep "" -c; grep "procs" /proc/stat; grep -R sleeping /proc/*/status | wc -l
 ps -eo stat | awk '/^S/ { stat+=1 } /^R/ { run +=1 } /^Z/ { zomb+=1 } { tot+=1 } END { print "sleeping = "stat" Running = "run" Zombie = "zomb" total = "tot }'

This will give you the same information about process state information.

R will be running processes, S will be sleeping processes and Z zombie.

Bear in mind top will always show one running process more as it will take the actual running of top into account.

  • For this top: Tasks: 191 total, 1 running, 190 sleeping, 0 stopped, 0 zombie |||| That returned: sleeping = 191 Running = 1 Zombie = total = 192 |||| Not bad :) – iletras Nov 24 '17 at 11:03

With a couple of exceptions, ps returns the correct answers.

local output=$(ps axo stat=)

cpu_tasks_running=$(echo -e "${output}" | grep -c  '^R')

cpu_tasks_sleeping=$(grep sleeping /proc/*/status | wc -l)
  # searching /proc gets better results than searching ps output:
  # cpu_tasks_sleeping=$(echo -e "${output}" | grep -cE '^D|^S')

cpu_tasks_stopped=$(echo -e "${output}" | grep -ci '^T')
cpu_tasks_zombie=$(echo -e "${output}" | grep -c  '^Z')

cpu_tasks_total=$(($cpu_tasks_running + $cpu_tasks_sleeping))
  # counting ps total lines never matched ps running + ps sleeping, nor top
  # replaced with math: ps running + ps sleeping
  # cpu_tasks_total=$(echo -e "${output}" | wc -l)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.