Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php system() shell_exec() hangs the browser [duplicate]

Tags:

php

shell-exec

Possible Duplicate:
Asynchronous shell exec in PHP

i need to run a java program in the background.

process.php contains

shell_exec("php php_cli.php")

php_cli.php contains

shell_exec("java -jar BiForce.jar settings.ini > log.txt");

I am calling process.php asynchronously using ajax

When i click the link in the webpage that calls ajax function (for running process.php) the webage shows "loading". when i click other links at the same time it does not responds.

The java program takes about 24 hours to finish executing, so user will not wait until the execution ends.

The problem is that the browser keeps on loading and does not go to other pages when clicked the link.

I also tried with system(), but the same problem ....

Help will greatly be appreciated.

like image 758
World Avatar asked Jun 03 '11 07:06

World


2 Answers

Using shell_exec waits for the command to hang up, so that's what your script is doing.

If your command doesn't have any wait time, then your script will not either.

You can call another PHP script from your original, without waiting for it to hang up:

$processId = shell_exec(
    "nohup " .                          // Runs a command, ignoring hangup signals.
    "nice " .                           // "Adjusted niceness" :) Read nice --help
    "/usr/bin/php -c " .                // Path to your PHP executable.
    "/path/to/php.ini -f " .            // Path to your PHP config.
    "/var/www/php_cli.php " .           // Path to the script you want to execute.
    "action=generate > /process.log " . // Log file.
    "& echo $!"                         // Make sure it returns only the process id.
    );

It is then possible to detect whether or not the script is finished by using this command:

exec('ps ' . $processId, $processState);
// exec returns the result of the command - but we need to store the process state.
// The third param is a referenced variable.

// First key in $processState is that it's running.
// Second key would be that it has exited.
if (count($processState) < 2) {
    // Process has ended.
}
like image 126
Greg Avatar answered Nov 19 '22 15:11

Greg


You could call the command in the page displayed, but appending an & at the end:

shell_exec("java -jar BiForce.jar settings.ini > log.txt &");

This way the process is launched on the background.

Also, there is no need (unless defined by your application) to create a process.php wich itself calls php via a shell exec. You could archive the same functionality via an include to the other file.

like image 2
Lumbendil Avatar answered Nov 19 '22 16:11

Lumbendil