Chris Russo
Chris Russo

Reputation: 480

PHP CLI console closing on error

I'm running a loop that executes the same application once the round is finished, using proc_open, like this:

$description = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "proc_open_errors", "a+")
);

$command = "start /min php $operador_php";
$process = proc_open($command, $description, $pipe);

if (is_resource($process)) {
    print_r($process);
    sleep(5);
    fclose($pipe[0]);
    fclose($pipe[1]);
    $process_response = proc_close($process);
    echo $process_response;
}

The issue I have is that after some hours running, one of the executions may fail in the middle, breaking the whole loop. And it closes itself (on Windows) so I can't see what the problem is.

Is there any way to prevent the PHP CLI from closing itself in case there's an issue? or should I rather use a sequence of "if /else" to check if there's any problem during the execution? Any other idea?

Upvotes: 0

Views: 1362

Answers (2)

Chris Russo
Chris Russo

Reputation: 480

Here's another solution I found on SO:

ini_set("log_errors", 1);
ini_set("error_log", "/php_error.log");
error_log( "Hello, errors!" );

I'd recommend placing the code at the beginning of the PHP file. I'd like to clarify, this is specially useful if you're interacting with other servers and the response it's not always the same, so this way, if there's any exception at 3 o'clock in the morning, it's gonna be saved at the file defined on the 2nd line.

Upvotes: 0

erik258
erik258

Reputation: 16304

You have options, but it depends on how you're executing it.

One option is to configure error handling in the php script. At least you can catch generic exceptions and log them before failing. Better yet, in many cases you might be able to recover from errors. Either way, http://php.net/manual/en/language.exceptions.php might be an interesting read.

A simpler approach, and perhaps a good place to start, would be to redirect output from the script into another file. Redirect Windows cmd stdout and stderr to a single file shows an easy invocation - works the same in unix. This way the window will still go away but you'll be able to view the logs separately. This is definitely a best practice when executing unattended scripts in any OS. Just make sure to handle the output file size reasonably ( if the php script is going to run forever, you'll have to do something more clever to keep the log from filling up your hard drive).

Finally, if you manually invoke the php script from the command line, I don't think the command line will exit when the script exits, but I guess I wouldn't be shocked if it did (as opposed to having windows auto-magically launch a shell for the process and then auto-magically close it when done ).

Upvotes: 1

Related Questions