Admia
Admia

Reputation: 1144

Status of process on linux

I have a list of pid's in the following array

All_Process_Pid

For each process, I want to check the status of process by using its pid.

More precisely, for each pid, I want to know if its corresponding process is -

  1. Running

  2. Done

  3. Stopped

How can I do this in bash?

Upvotes: 6

Views: 18637

Answers (1)

Facundo Victor
Facundo Victor

Reputation: 3518

First of all, there are more process states than "Running", "Done" and "Stopped", 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

You can get the status of one process by its pid (process ID) using the command ps:

ps -q <pid> -o state --no-headers

From man ps:

-q pidlist
     Select by PID (quick mode).  This selects the processes whose
     process ID numbers appear in pidlist.  With this option ps reads the
     necessary info only for the pids listed in the pidlist and doesn't
     apply additional filtering rules. The order of pids is unsorted and
     preserved. No additional selection options, sorting and forest type
     listings are allowed in this mode.  Identical to q and --quick-pid.

If you have the array of pid "All_Process_Pid" in your bash script, then you can just:

for i in "${All_Process_Pid[@]}"
do
     echo "process $i has the state $(ps -q $i -o state --no-headers)"
done

Upvotes: 16

Related Questions