PHP Execute a Background Process

php execute a background process

Assuming this is running on a Linux machine, I've always handled it like this:

exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));

This launches the command $cmd, redirects the command output to $outputfile, and writes the process id to $pidfile.

That lets you easily monitor what the process is doing and if it's still running.

function isRunning($pid){
try{
$result = shell_exec(sprintf("ps %d", $pid));
if( count(preg_split("/\n/", $result)) > 2){
return true;
}
}catch(Exception $e){}

return false;
}

php exec() background process issues

Note:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

http://php.net/manual/en/function.exec.php

so:

exec("php csv.php $file $user > /dev/null &"); // no $output

Running a PHP exec() in the background on Windows?

Include a redirection in the command line:

exec('program.exe > NUL')

or you could modify your program to explicitly close standard output, in C this would be

CloseHandle(GetStdHandle(STD_OUTPUT_HANDLE));

It is possible (the documentation doesn't say) that you might need to redirect/close both the standard output and standard error:

exec('program.exe > NUL 2> NUL')

or

CloseHandle(GetStdHandle(STD_OUTPUT_HANDLE));
CloseHandle(GetStdHandle(STD_ERROR_HANDLE));

php background process using exec function

You have to reroute programs output somewhere too, usually /dev/null

exec($cmd . " > /dev/null &");

shell_exec not running in background?

exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));

php execute a background process

exec("/usr/bin/php /path/background.php > /dev/null 2>&1 &");

php in background exec() function

exec() will block until the process you're exec'ing has completed - in otherwords, you're basically running your 'test.php' as a subroutine. At bare minimum you need to add a & to the command line arguments, which would put that exec()'d process into the background:

exec("php test.php {$test['id']} &");

How to run a background process by PHP in windows?

I checked PHP: popen - Manual and see there a is not a valid mode, but I see this on several answers around here!

however:

The mode. Either 'r' for reading, or 'w' for writing.

By changing mode to r, the script call and run in the background correctly and there is not an error or warning on PHP or Py.

<?PHP
$python = 'C:\\Users\\User\\anaconda3\\python.exe';
$py_script = 'C:\\wamp\\www\\lab\\ex\\simple_test.py';
$py_stdout = '> temp\\'.session_id()."_std.txt";
$py_stderror = '2> temp\\'.session_id()."_stde.txt";
$py_cmd = "$python $py_script $py_arg_1 $py_std $py_stde";

pclose(popen("start /B ". $py_cmd, "r"));


Related Topics



Leave a reply



Submit