Sandro Antonucci
Sandro Antonucci

Reputation: 1753

how to check if a PHP script is running ?

If I launch a PHP daemon in Windows with popen from a PHP script how do I check in a second time if that script is still running from a PHP script?

I'm with Apache, php as module

UPDATE: process it's started with

popen('start /b php process.php', 'r');

Once this is launched in windows a php.exe process is started. How do I get that process PID to later check (it runs for hours) from another PHP script if that process is still running?

I read this proc_open which is supposed to give the PID of the process launched along with proc_get_status but with that same command I use with popen nothing happens

UPDATE: I noticed with the same command and proc_open a php.exe process does start but it closes just after the script that launched it ends and the PID returned by proc_get_status doesn't correspond to the Windows PID

Upvotes: 1

Views: 2183

Answers (2)

hohner
hohner

Reputation: 11588

There are several ways of safely running processes with PHP and Windows:

1. Start background process using the WScript.Shell object

You can start the process using the Run method of the WScript.Shell object, which is built-in to Windows. By varying the second parameter, you can make the window hidden, visible, minimized, etc. By setting the third parameter to false, Run does not wait for the process to finish executing. This code only works on Windows. To find out more about COM, read PHP's documentation.

$WshShell = new COM("WScript.Shell");
$oExec = $WshShell->Run("cmd /C dir /S %windir%", 0, false);

2. Start background process using popen and pclose

This code should work on Linux and Windows.

pclose(popen("start \"bla\" \"" . $exe . "\" " . escapeshellarg($args), "r"));

3. Start background process with psexec

This method requires installing the freeware pstools from sysinternals:

exec("psexec -d blah.bat"); 

You can find out more information about it by reading this brief tutorial. I've used the first method before and it's always worked for me.


To find the PID of an existing process, I don't think you can use getmypid or posix_getpid so you'll have to use exec('tasklist');. Alternatively, you can install this extension and follow these instructions.

Upvotes: 2

user1286094
user1286094

Reputation: 121

use system() from php

and

Working with cmd.exe:

tasklist

If you have Powershell:

get-process

not tested. Or write your small console app with winapi calls

Upvotes: 0

Related Questions