首页 > 解决方案 > 如何通过 shell_exec() 获取特定进程的状态?

问题描述

我想通过在命令中传递名称来了解进程的状态,并使用函数 shell_exec() 执行它。

我试过这个:

` 
  $checkProcessStatus = "ps aux | grep <ProcessName>";
  $status = shell_exec($checkProcessStatus);
  dd($status);
`

我得到了这个结果:

`
 user 17072  0.0  0.2 166216 33332 pts/3    S+   11:31   0:00 <ProcessName> artis
 user 20397  0.0  0.0  14232   868 pts/3    S+   11:52   0:00 grep <ProcessName>
`

我只想要“跑步”或“睡眠”等状态。

标签: php

解决方案


这是工作代码:

<?php
$command = 'ps aux';
$result = shell_exec($command);
//split for rows
$processes = explode("\n", $result);
//delete head row
array_shift($processes);
//analyze
foreach ($processes as $rawProcess) {
    //beware, command line column may include spaces, that why last group is (.+)
    preg_match('/(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)/', $rawProcess,$matches);
    //preg match doesn't find anything
    if (empty($matches)) {
        continue;
    }
    //is sleeping status
    if (strpos($matches[8], 'S') === 0) {
        echo $rawProcess;
        echo "\n";
        continue;
    }
    //is running status
    if (strpos($matches[8], 'R') === 0) {
        echo $rawProcess;
        echo "\n";
        continue;
    }
    //is not sleeping and not running status
}

您可以将 $matches[N] 用于任何列。

顺便说一句,您可以使用 awk 按状态 grep 数据

ps aux | awk 'substr($8,1,1) == "S" || substr($8,1,1) == "R"'

附言

状态意味着:

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

状态加法平均值

<    high-priority (not nice to other users)
N    low-priority (nice to other users)
L    has pages locked into memory (for real-time and custom IO)
s    is a session leader
l    is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)
+    is in the foreground process group

推荐阅读