PHP shell_exec - how to terminate the process if the connection is closed?
我有一个有效的PHP脚本,使用shell_exec执行外部程序,大约需要30秒才能完成。
问题是,如果用户关闭浏览器或由于某种原因关闭了连接,用shell_exec执行的程序将继续运行,因为它的输出无法再发送给用户。
连接关闭后,是否有办法终止此过程?
谢谢您的帮助。
终于我解决了!
我已经使用PHP函数
http://us2.php.net/manual/zh/function.connection-aborted.php
算法如下(伪代码)
1 2 3 4 5 6 7 8 9 10 | 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 2 3 4 |
并使用它杀死具有给定ProcessID的进程
1 |
您可以创建一个运行/执行/停止正在运行的php脚本的管理器。 该脚本将不断运行(可能作为守护程序运行),并检查脚本/进程的状态,用户状态,如果用户不在,则关闭脚本。 我认为您可以使用Sockets做到这一点。
如何在JavaScript HTML中使用套接字?
http://php.net/manual/zh/book.sockets.php