Home >Backend Development >PHP Tutorial >How Can I Get Real-Time Process Output and Gracefully Kill Processes in PHP?

How Can I Get Real-Time Process Output and Gracefully Kill Processes in PHP?

DDD
DDDOriginal
2024-12-19 17:28:14668browse

How Can I Get Real-Time Process Output and Gracefully Kill Processes in PHP?

Real-Time Process Output in PHP

Running processes that output in real-time on a web page can enhance user experience and provide immediate feedback. In PHP, it's possible to achieve this using the proc_open() function.

Obtaining Real-Time Output

To obtain real-time output from a process, use proc_open() as follows:

$cmd = "ping 127.0.0.1";
$descriptorspec = array(
    0 => array("pipe", "r"),
    1 => array("pipe", "w"),
    2 => array("pipe", "w")
);

$process = proc_open($cmd, $descriptorspec, $pipes, realpath('./'), array());

// Display output
echo "<pre class="brush:php;toolbar:false">";
if (is_resource($process)) {
    while ($s = fgets($pipes[1])) {
        print $s;
        flush();
    }
}
echo "
";

In this code, the ping process's output is continuously read from the pipe $pipes[1] and displayed.

Killing the Process on Page Exit

To kill a process when a page is exited, use the following code:

register_shutdown_function(function() use ($process) {
    proc_terminate($process);
    // Wait for process to terminate gracefully
    proc_close($process);
});

This code registers a shutdown function that terminates a process when the script exits. It also gracefully waits for the process to finish before closing it.

By leveraging proc_open() and register_shutdown_function(), you can execute processes and obtain their real-time output in PHP. When the page exits, the process is automatically terminated to prevent any lingering system resources.

The above is the detailed content of How Can I Get Real-Time Process Output and Gracefully Kill Processes in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn