Use PHP proc_open + bypass_shell to run the executable in the background and get the correct PID?

So, in PHP on Windows: is it possible to execute an executable file in the background and get its PID ? I came to the conclusion that you can perform both tasks separately, but not together.

Process Background

To execute a background process launched via SHELL, you must use the command 'start /B "bg" myprog.exe'and the SHELL process must be immediately closed.

To do this, many use the pclose( popen( ... ) )way, pclose( popen( 'start /B "bg" myprog.exe', 'r') );but, as far as I know, it is impossible to get pidwhen using popen.

Since it is not possible to get pidwith popen, we should look at proc_open.

Getting PID

Using proc_open, we can get pid exe if , and only if the parameter is bypass_shell set to true.

If the parameter is bypass_shellset to false (default), Windows returns a value pidfor SHELL. For more information see: https://bugs.php.net/bug.php?id=41052

Explanation of the problem

The command start /Bcrashes when passing proc_open when bypass_shell = true, because it skips SHELL and sends the command line arguments directly to the myprog.exe file, which does not know what to do with them.

, If bypass_shell = false ( ) proc_close SHELL, myprog.exe , pclose( popen( ... ) ), pid ( pid SHELL).

, backgrounding + pid?

, ? PHP script, , . , , - tasklist myprog.exe , . , 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];
+5
1

OP, Windows, Linux- exec(), -;)

$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);
+1

All Articles