简体   繁体   English

PHP:获取命令的 LINUX PID

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

I'm running a command in my linux server (Ubuntu).我在我的 linux 服务器(Ubuntu)中运行一个命令。 For example:例如:

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

Is there any way to the PID of this background progress which screen name is: test_command_one ?有没有办法获得这个后台进程的PID,屏幕名称是: test_command_one

ps aux | ps辅助| grep test_command_one: grep test_command_one:

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

I'd like to get back this PID: 6573我想取回这个PID: 6573

PHP: (easy) PHP:(简单)

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

Thanks for help!感谢帮助!

Edit:编辑:

By combining with code by @WagnerVaz通过与@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];

Explanation解释

  • ps aux - shows processes for all users and hidden processes too ps aux - 显示所有用户和隐藏进程的进程
  • grep - filters only lines containing "screen" and then "test_command_one" in the same line grep - 仅过滤包含“screen”的行,然后在同一行中过滤“test_command_one”
  • grep -v - removes from output the very same line which we are executing, because it will also be matched grep -v - 从输出中删除我们正在执行的同一行,因为它也会被匹配
  • awk '{ print $2 }' - awk splits input into columns and uses multiple spaces as separator. awk '{ print $2 }' - awk 将输入分成列并使用多个空格作为分隔符。 This print contents of 2nd column此打印第 2 列的内容
  • head -1 - limits output only to the first line. head -1 - 将输出限制为仅第一行。 This is in case you have multiple screen running, only first ID is returned.这是在您有多个屏幕运行的情况下,只返回第一个 ID。

Try this:试试这个:

<?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];
?>

Edited: Combined with shell exec of @romaninsh编辑:结合@romaninsh的shell exec

You could also try this:你也可以试试这个:

echo exec('pidof test_command_one');

It's shorter ;)它更短;)

See also: pidof manpage另请参阅: pidof 联机帮助页

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

或者,只需使用:

$pid = getmypid();

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

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