Home > Backend Development > PHP Tutorial > How to Execute and Terminate Realtime PHP Processes?

How to Execute and Terminate Realtime PHP Processes?

Patricia Arquette
Release: 2024-12-05 08:26:11
Original
686 people have browsed it

How to Execute and Terminate Realtime PHP Processes?

Realtime Process Execution and Termination in PHP

This question explores how to execute a process on a web page and receive its output in real time, eliminating the need to wait until the process completes. The second part of the question addresses how to terminate such processes when a user leaves the page.

One method for executing processes in PHP and streaming their output is through the proc_open() function. This function allows for the creation of a child process that can run independently from the parent PHP process. To facilitate real-time output, you can specify the $descriptorspec parameter with appropriate file descriptors to capture the process's stdout and stderr streams.

$cmd = "ping 127.0.0.1";

$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
);

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

Once the child process is created, you can use a loop to continuously read from the stdout pipe and print the output.

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

To terminate the child process when the user leaves the page, you can use a PHP shutdown function. Shutdown functions are executed when the PHP script terminates, which can occur when a user closes a browser tab or navigates away from the page. In the shutdown function, you can call proc_close() on the child process handle to terminate it.

register_shutdown_function(function() {
  proc_close($process);
});
Copy after login

The above is the detailed content of How to Execute and Terminate Realtime PHP Processes?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template