Execute Background Processes in PHP
Many web applications require performing time-consuming tasks, such as directory copying. To enhance user experience, it's desirable to execute these tasks in the background without disrupting the user interface.
Background Process Execution in PHP:
In PHP, executing processes in the background can be challenging. However, for Linux environments, a common solution is to use the exec function:
exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));
This command achieves the following:
Process Monitoring:
To monitor the progress of the background process, a helper function can be used:
function isRunning($pid){ try{ $result = shell_exec(sprintf("ps %d", $pid)); if( count(preg_split("/\n/", $result)) > 2){ return true; } }catch(Exception $e){} return false; }
This function allows you to check if the process with the specified PID is still running, based on the output of the ps command.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3