PHP:获取命令的 LINUX PID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7829005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Get the LINUX PID of a command
提问by Skylineman
I'm running a command in my linux server (Ubuntu). For example:
我在我的 linux 服务器(Ubuntu)中运行一个命令。例如:
screen -A -h 1500 -m -dmS test_command_one /home/SKY-users/SKY-001/./script
Is there any way to the the PID of this background progress which screen name is: test_command_one
?
有什么办法可以得到这个后台进程的PID,屏幕名称是:test_command_one
?
ps aux | grep 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/./ ...
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!
感谢帮助!
采纳答案by romaninsh
Edit:
编辑:
By combining with code by @WagnerVaz
通过与@WagnerVaz 的代码结合
$mystring = "test_command_one";
exec("ps aux | grep 'screen .* $mystring' | grep -v grep | awk '{ print }' | head -1", $out);
print "The PID is: " . $out[0];
Explanation
解释
- ps aux - shows processes for all users and hidden processes too
- grep - filters only lines containing "screen" and then "test_command_one" in the same line
- grep -v - removes from output the very same line which we are executing, because it will also be matched
- awk '{ print $2 }' - awk splits input into columns and uses multiple spaces as separator. This print contents of 2nd column
- head -1 - limits output only to the first line. This is in case you have multiple screen running, only first ID is returned.
- ps aux - 显示所有用户和隐藏进程的进程
- grep - 仅过滤包含“screen”的行,然后在同一行中过滤“test_command_one”
- grep -v - 从输出中删除我们正在执行的同一行,因为它也会被匹配
- awk '{ print $2 }' - awk 将输入分成列并使用多个空格作为分隔符。此打印第 2 列的内容
- head -1 - 将输出限制为仅第一行。这是在您有多个屏幕运行的情况下,只返回第一个 ID。
回答by 0xd
Try this:
尝试这个:
<?php
$mystring = "test_command_one";
exec("ps aux | grep \"${mystring}\" | grep -v grep | awk '{ print }' | head -1", $out);
print "The PID is: " . $out[0];
?>
Edited: Combined with shell exec of @romaninsh
编辑:结合@romaninsh的shell exec
回答by sneils
You could also try this:
你也可以试试这个:
echo exec('pidof test_command_one');
It's shorter ;)
它更短;)
See also: pidof manpage
另请参阅:pidof 联机帮助页
回答by Juancho Ramone
$pid = shell_exec($cmd . " && echo $!");
回答by Christian Melius
Or, just use:
或者,只需使用:
$pid = getmypid();