Are there best practices for handling long-running shell commands in PHP scripts?

When running long-running shell commands in PHP scripts, it is important to handle them properly to prevent timeouts and ensure the script runs smoothly. One common approach is to use the `proc_open()` function to execute the command asynchronously and then read the output incrementally to avoid memory issues.

$descriptorspec = array(
    0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
    1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
    2 => array("pipe", "w")   // stderr is a pipe that the child will write to
);

$process = proc_open('long_running_command', $descriptorspec, $pipes);

if (is_resource($process)) {
    stream_set_blocking($pipes[1], 0); // Set stdout to non-blocking mode

    while (($line = fgets($pipes[1])) !== false) {
        // Process the output line by line
        echo $line;
    }

    fclose($pipes[1]);
    proc_close($process);
}