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.

Parris Varney
  • 11,320
  • 12
  • 47
  • 76
  • 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. – dqhendricks Dec 30 '10 at 17:59
  • 1
    The '0' you get probably means that the process was successfully sent to background. – Álvaro González Dec 30 '10 at 17:59
  • Please refer this link http://stackoverflow.com/questions/1533675/php-exec-return-value-for-background-process-linux – Pradeep Singh Dec 30 '10 at 17:58

2 Answers2

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) {
 ...
}
Parris Varney
  • 11,320
  • 12
  • 47
  • 76
  • 1
    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 Feb 06 '13 at 14:10
  • @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. – Parris Varney Feb 06 '13 at 21:42
  • no worry, was searching for something similar (unrelated to background processes), read the accepted answer and felt the need to point out possible issues... – Khez Feb 07 '13 at 07:28
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

Kyle
  • 2,822
  • 2
  • 19
  • 24