繁体   English   中英

PHP:获取命令的 LINUX PID

[英]PHP: Get the LINUX PID of a command

我在我的 linux 服务器(Ubuntu)中运行一个命令。 例如:

screen -A -h 1500 -m -dmS test_command_one /home/SKY-users/SKY-001/./script

有没有办法获得这个后台进程的PID,屏幕名称是: test_command_one

ps辅助| grep test_command_one:

root      6573  8.1  2.4 271688 123804 pts/4   Ss+  Oct19   3:04 /home/SKY-users/SKY-001/./ ...

我想取回这个PID: 6573

PHP:(简单)

<?php 
$output = shell_exec('sudo ps aux | grep test_command_one');
$array = explode("\n", $output);
echo '<pre>'.print_r($array, true).'</pre>';
?>

感谢帮助!

编辑:

通过与@WagnerVaz 的代码结合

$mystring = "test_command_one";
exec("ps aux | grep 'screen .* $mystring' | grep -v grep | awk '{ print $2 }' | head -1", $out);
print "The PID is: " . $out[0];

解释

  • ps aux - 显示所有用户和隐藏进程的进程
  • grep - 仅过滤包含“screen”的行,然后在同一行中过滤“test_command_one”
  • grep -v - 从输出中删除我们正在执行的同一行,因为它也会被匹配
  • awk '{ print $2 }' - awk 将输入分成列并使用多个空格作为分隔符。 此打印第 2 列的内容
  • head -1 - 将输出限制为仅第一行。 这是在您有多个屏幕运行的情况下,只返回第一个 ID。

试试这个:

<?php
    $mystring = "test_command_one";
    exec("ps aux | grep \"${mystring}\" | grep -v grep | awk '{ print $2 }' | head -1", $out);
    print "The PID is: " . $out[0];
?>

编辑:结合@romaninsh的shell exec

你也可以试试这个:

echo exec('pidof test_command_one');

它更短;)

另请参阅: pidof 联机帮助页

$pid = shell_exec($cmd . " && echo $!");

或者,只需使用:

$pid = getmypid();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM