linux上的进程状态

Adm*_*mia 3 bash pid process status

pid在以下数组中有一个's列表

All_Process_Pid
Run Code Online (Sandbox Code Playgroud)

对于每个进程,我想通过使用其pid.

更准确地说,对于每个pid,我想知道其对应的过程是否是 -

  1. 跑步

  2. 完毕

  3. 停止

我怎样才能在 bash 中做到这一点?

Fac*_*tor 10

首先,来自man ps 的进程状态比“Running”、“Done”和“Stopped”更多:

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
Run Code Online (Sandbox Code Playgroud)

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

ps -q <pid> -o state --no-headers
Run Code Online (Sandbox Code Playgroud)

来自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.
Run Code Online (Sandbox Code Playgroud)

如果您的 bash 脚本中有 pid 数组“All_Process_Pid”,那么您可以:

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