如何从 Windows 中的 PHP 函数 exec() 获取 PID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3679663/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:13:54  来源:igfitidea点击:

How to get PID from PHP function exec() in Windows?

phpwindowsbackgroundexecbackground-process

提问by jarkam

I have always used:

我一直使用:

$pid = exec("/usr/local/bin/php file.php $args > /dev/null & echo $!");

But I am using an XP virtual machine to develop a web app and I have no idea how to get the pid in windows.

但是我正在使用 XP 虚拟机来开发 Web 应用程序,我不知道如何在 Windows 中获取 pid。

I tried this on a cmd:

我在 cmd 上试过这个:

C:\wamp\bin\php\php5.2.9-2\php.exe "file.php args" > NUL & echo $!

And it gets the file executed, but the output is "$!"

它执行文件,但输出是“$!”

How can I get the pid into the var $pid? (using php)

如何将 pid 放入 var $pid 中?(使用 php)

采纳答案by Jim W.

You will have to install an extra extension, but found the solution located at Uniformserver's Wiki.

您将不得不安装一个额外的扩展,但在Uniformserver 的 Wiki 中找到了解决方案。

UPDATE

更新

After some searching you might look into tasklistwhich coincidently, you may be able to use with the PHP execcommand to get what you are after.

经过一些搜索,您可能会tasklist偶然发现,您可以使用 PHPexec命令来获得您想要的东西。

回答by SeanDowney

I'm using Pstoolswhich allows you to create a process in the background and capture it's pid:

我正在使用Pstools,它允许您在后台创建一个进程并捕获它的 pid:

// use psexec to start in background, pipe stderr to stdout to capture pid
exec("psexec -d $command 2>&1", $output);
// capture pid on the 6th line
preg_match('/ID (\d+)/', $output[5], $matches);
$pid = $matches[1];

It's a little hacky, but it gets the job done

这有点hacky,但它完成了工作

回答by Diggy Dude

Here's a somewhat less "hacky" version of SeanDowney's answer.

这是 SeanDowney 答案的一个不那么“hacky”的版本。

PsExec returns the PID of the spawned process as its integer exit code. So all you need is this:

PsExec 返回衍生进程的 PID 作为其整数退出代码。所以你只需要这个:

<?php

    function spawn($script)
    {
      @exec('psexec -accepteula -d php.exe ' . $script . ' 2>&1', $output, $pid);
      return $pid;
    } // spawn

    echo spawn('phpinfo.php');

?>

The -accepteula argument is needed only the first time you run PsExec, but if you're distributing your program, each user will be running it for the first time, and it doesn't hurt anything to leave it in for each subsequent execution.

-accepteula 参数仅在您第一次运行 PsExec 时才需要,但如果您正在分发您的程序,则每个用户都将第一次运行它,并且在每次后续执行时都保留它不会有任何伤害。

PSTools is a quick and easy install (just unzip PSTools somewhere and add its folder to your path), so there's no good reason not to use this method.

PSTools 是一种快速简便的安装(只需将 PSTools 解压缩到某处并将其文件夹添加到您的路径中),因此没有充分的理由不使用此方法。