How to get PID from PHP function exec() in

2020-06-03 04:31发布

问题:

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.

I tried this on a 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)

回答1:

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

UPDATE

After some searching you might look into tasklist which coincidently, you may be able to use with the PHP exec command to get what you are after.



回答2:

I'm using Pstools which allows you to create a process in the background and capture it's 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



回答3:

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

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

<?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.

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.