问题
I have a working php script using shell_exec to execute an external program that take about 30 seconds to complete. Problem is that if an user close the browser or the connection is closed for some reason the program executed with shell_exec continue to run for nothing, since it's output can't be sent to the user anymore.
Is there a way to kill this process as soon as the connection is closed?
Thank you for your help.
回答1:
Finally I've solved it!
I've used the PHP function connection_aborted()
to check if the client is disconnected.
http://us2.php.net/manual/en/function.connection-aborted.php
The algorithm is the following (pseudocode)
shell_exec("script");//script is a shell script that launch the program in another thread thus this return immediately
$task_completed=false;
while(!$task_completed){
if(connection_aborted()==1){
kill_the_process();//this will kill the running process launched by script
die();
}
$task_completed=...;//true if the task completed
sleep(1);
}
回答2:
You could make a manager that runs/executes/stops the running php scripts. This script would run constantly -maybe as daemon- and check the status of the script/process, the user status and close the script if the user is gone. I think you could do this well with Sockets.
How to Use Sockets in JavaScript\HTML?
http://php.net/manual/en/book.sockets.php
回答3:
you can use to get the list of all running process
$res = shell_exec('ps -x');
$res = explode("\n",$res);
print_r($res);
and use this to kill process with given ProcessID
shell_exec('kill -KILL ProcessID');
来源:https://stackoverflow.com/questions/16103082/php-shell-exec-how-to-terminate-the-process-if-the-connection-is-closed