Linux上的进程状态

时间:2015-11-29 03:52:38

标签: bash process status pid

我在以下数组中有pid的列表

All_Process_Pid

对于每个流程,我想使用其pid检查流程的状态。

更确切地说,对于每个pid,我想知道它的相应过程是否为 -

  1. 正在运行

  2. 完成

  3. 停止

  4. 我怎样才能在bash中这样做?

1 个答案:

答案 0 :(得分:3)

首先,进程状态多于"运行","完成" "停止",来自 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

您可以使用 ps 命令通过其pid(进程ID)获取一个进程的状态:

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

来自 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.

如果你有pid数组&#34; All_Process_Pid&#34;在你的bash脚本中,你可以只是:

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