Linux系统进程状态

5

以下是一个包含 pid 的列表的数组:

All_Process_Pid

对于每个进程,我想通过使用其pid来检查进程的状态。
更准确地说,对于每个pid,我想知道其相应的进程是否处于以下状态之一:
1. 运行中 2. 已完成 3. 已停止
我该如何在bash中实现这一点?

请在解决此问题时表现出一些合理的意图,包括一些示例代码,并记住 Stack Overflow 不是编写代码的服务。 - SwiftArchitect
1个回答

14

首先,与“运行”,“完成”和“停止”不同的是,有更多的进程状态,参考 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 通过进程ID(pid)获取一个进程的状态:
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.

如果您的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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接