7

Is there anyway to get the exit status code for a php script run in the background via exec($cmd, $output, $exitCode)?

For example:

exec('php script.php &', $output, $exitCode); 

If the trailing '&' isn't included then $exitCode works as expected, it's always 0 otherwise.

3
  • Please refer this link stackoverflow.com/questions/1533675/… Commented Dec 30, 2010 at 17:58
  • 2
    not positive, but i think if it is running in the background, then your code moves on before the called script finishes execution, so there is no way to get the returned status code. Commented Dec 30, 2010 at 17:59
  • 1
    The '0' you get probably means that the process was successfully sent to background. Commented Dec 30, 2010 at 17:59

2 Answers 2

6

For anybody that finds themselves here, my solution was to make a php script that takes a script as an argument. The new script is called to the background and handles exit statuses appropriately.

For example:

$cmd = 'php asynchronous_script.php -p 1';
exec("php script_executor.php -c'$cmd' &");

The second script looks something like

$opts = getOpt('c:');
$cmd = rtrim($opts['c'], '&');
$exitCode = 0;
$output = '';

exec($cmd, $output, $exitCode);

if ($exitCode > 0) {
 ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

Aren't you removing & in the second script? Meaning you are not running a background process in either case? You probably meant to run the first script in the background... probably.
@Khez It's been a while since I posted this, but I think you're right, the original solution had a hard coded & in the first exec() call, and removed it from the second so it could deal with the exit codes.
no worry, was searching for something similar (unrelated to background processes), read the accepted answer and felt the need to point out possible issues...
5

I found something that is probably quite equivalent to Pradeep's solution. Someone posted about this on the function's documentation page. http://www.php.net/manual/en/function.exec.php#101506

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.