php - 如何通过 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
$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
推荐阅读
- blazor - Blazor 上的hangfire RecurringJob
- python-3.x - python - 如何在python pandas中对以数据框的某个单词结尾的某些列求和?
- java - 具有多个手机客户端的 Spring Boot TCP 服务器
- swift - 视图控制器显示为弹出窗口
- gnuplot - 具有自定义范围的 Gnuplot 偏移量 (v5.4)
- mysql - 我如何将动态表单的值从反应发送到节点 js
- c - C语言:给定一个字符串,删除/删除包含n个元音的单词
- c++ - 如何修复代码块(语言 C)中的 ssrteam 致命错误?
- python - 带有“secondary_y”的 Matplotlib:如何将图例重新定位到左下角?
- shell - 如何在awk中修改来自ifconfig的输入