PHP shell_exec - 如果连接关闭,如何终止进程?

时间:2013-04-19 11:00:24

标签: php shell-exec terminate

我有一个使用shell_exec的php脚本来执行一个大约需要30秒才能完成的外部程序。 问题是,如果用户关闭浏览器或连接由于某种原因而关闭,使用shell_exec执行的程序将继续运行,因为它的输出无法再发送给用户。

连接关闭后是否有办法终止此过程?

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

最后我解决了!

我已经使用PHP函数connection_aborted()来检查客户端是否已断开连接。 http://us2.php.net/manual/en/function.connection-aborted.php

算法如下(伪代码)

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

答案 1 :(得分:0)

你可以让管理员运行/执行/停止正在运行的php脚本。此脚本将不断运行 - 可以作为守护程序 - 并检查脚本/进程的状态,用户状态并在用户离开时关闭脚本。我认为你可以用套接字很好地做到这一点 How to Use Sockets in JavaScript\HTML?
http://php.net/manual/en/book.sockets.php

答案 2 :(得分:0)

您可以用来获取所有正在运行的进程的列表

$res = shell_exec('ps -x');
$res = explode("\n",$res);
print_r($res);

并使用它来杀死给定 ProcessID

的进程
shell_exec('kill -KILL ProcessID');