gpt4 book ai didi

php - 使用 PHP 的 proc_open + bypass_shell 在后台运行可执行文件并检索正确的 PID?

转载 作者:可可西里 更新时间:2023-11-01 13:47:40 26 4
gpt4 key购买 nike

那么,在 Windows 上的 PHP 中:是否可以同时在后台运行可执行文件检索其 PID?我推断可以单独完成这两项任务,但不能同时完成。

后台处理

要使通过 SHELL 启动的进程后台运行,必须使用命令 'start/B "bg"myprog.exe' 并且 SHELL 进程必须在之后立即关闭。

为此,许多人使用 pclose( popen( ... ) ) 像这样 pclose( popen( 'start/B "bg"myprog.exe', 'r' ) ); 但据我所知,使用 popen 时无法检索 pid

因为不可能用 popen 得到 pid,所以我们必须查看 proc_open。

获取PID

如果且仅当 bypass_shell 设置为 true 时,我们可以使用 proc_open 检索 exe 的 pid。

如果 bypass_shell 设置为 false(默认值),Windows 将返回 SHELL 的 pid。有关详细信息,请参阅:https://bugs.php.net/bug.php?id=41052

问题解释

start/B 命令在 bypass_shell = true 时传递给 proc_open 时失败,因为它跳过 SHELL 并将命令行参数直接发送到 myprog.exe,而 myprog.exe 不会知道如何处理它们。

相反,如果 bypass_shell = false(默认值)和 proc_close 用于立即关闭 SHELL,myprog.exe 在后台运行,就像使用 pclose( popen( .. . ) ) 但是 不正确 pid 被返回(我们得到了 SHELL 的 pid)。

那么,后台 + 正确的 pid 检索可能吗?

如果不是,下一个最好的是什么?我需要为将部署在共享主机上的 PHP 脚本执行此操作,因此无法安装第三方扩展。我能想到的最好办法是在后台启动 myprog.exe 之前和之后拍摄 tasklist 的快照,然后交叉分析结果。请注意,myprog.exe 可以同时运行。

如果有帮助,尽管应该没什么区别,但 myprog.exe 实际上是 ffmpeg(安装在大多数共享网络主机上)。

临时解决方案

// background the process
pclose( popen( 'start /B "bg" ffmpeg.exe', 'r') );

// get the pid using tasklist
exec( 'TASKLIST /NH /FO "CSV" /FI "imagename eq ffmpeg.exe" /FI "cputime eq 00:00:00"', $output );
$output = explode( '","', $output[0] );
$pid = $output[1];

最佳答案

这不完全是 OP 问题的答案,因为它不能在 Windows 服务器上运行,但它可以在任何启用了 exec() 的 linux 服务器上正常运行,因此它可能对某些人有帮助;)

$pidfile = 'myPidFile'; //coule be done better with tempnam(), but for this example will do like that ;)
$outputfile = '/dev/null'; //can be any text file instead of /dev/null. output from executable will be saved there
$cmd = 'sleep 30'; // this would normaly take 30 seconds
exec(sprintf("%s > %s 2>&1 & echo $! > %s", $cmd, $outputfile, $pidfile));

$pid = file_get_contents($pidfile);
echo $pid;
//delete pid file if you want
//unlink($pidfile);

关于php - 使用 PHP 的 proc_open + bypass_shell 在后台运行可执行文件并检索正确的 PID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7161454/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com