xtempore
xtempore

Reputation: 5505

Asynchronous PHP script stops when main script stops

I spent some time trying to find a way on Windows to have a PHP script start another script asynchronously, and came across a suggested solution of using popen(). It didn't seem to work at first, but then when I added a delay it seemed to work a bit better. But on further investigation, it seems that shortly after the main script ends, the secondary process is killed.

Here's the relevant bit of code that launches the secondary script...

$cmd = <<<EOT
start "php" /b "C:\\Program Files (x86)\\iis express\\PHP\\v7.1\\php.exe" -f="$script" $args
EOT;
$p = popen($cmd, 'r');
usleep(500000);
pclose($p);

And the relevant part of the secondary script...

$fp = fopen($argv[1] . '.txt', 'w');
for ($i = 0; $i < 100; $i++) {
    fwrite($fp, $i ."\n");
    sleep(1);
}
fclose($fp);

This is just proof-of-concept stuff. Basically, the second script opens a file and then writes numbers from 0 to 99 at 1-second intervals.

The problem is that it doesn't seem to finish. If the sleep is for 500ms it only gets to about 15. For 200ms it gets to around 8, etc.

I'm guessing that it's some sort of process ownership issue. E.g. when the primary script terminates it kills off child processes, but I'm not sure and have run out of ideas of what else to try.

(Running IIS on Windows 10)

Any suggestions?

Upvotes: 0

Views: 81

Answers (1)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21671

You can run it on windows like so: using COM and WScript.Shell

$WshShell = new COM('WScript.Shell');
$cmd = 'cmd /C php '.$script;
$oExec = $WshShell->Run($cmd, 0, false);

This only works on windows, on Linux you can run it.

$cmd = 'php -f '.$script.' > /dev/null &';
exec($cmd, $oExec);

Both run a non-blocking background process. This does assume you added the path to the php.exe to your environmental variables in windows, if not you can use the full path to the executable.

Don't ask me how many hours I spent figuring this out, it was a few. As for popen well I never got that to work either, but than sending info to it through a pipe or whatnot wasn't a concern for me.

Upvotes: 1

Related Questions