gpt4 book ai didi

PHP - 在客户端断开连接时杀死 exec

转载 作者:可可西里 更新时间:2023-10-31 23:33:16 25 4
gpt4 key购买 nike


我的 C++ 应用程序有非常原始的 Web 前端。客户端(网络浏览器)进入 php 站点并使用参数填写表单。然后(在提交后)php 调用 exec 并且应用程序开始工作。应用程序可以工作超过一分钟,并且需要相当大的 RAM。

是否有可能检测到与客户端的断开连接(例如关闭网络浏览器中的选项卡)。我想这样做,因为断开连接后客户端将无法看到计算结果,因此我可以终止应用程序并释放服务器上的一些 RAM。

感谢任何帮助或建议。

最佳答案

只要 C++ 程序在运行时产生输出,而不是在终止之前产生所有输出,就使用 passthru() 而不是 exec()

这会导致 PHP 在生成内容时将输出刷新到客户端,从而允许 PHP 检测客户端何时断开连接。当客户端断开连接时,PHP 将终止并立即终止子进程(只要未设置 ignore_user_abort())。

例子:

<?php

function exec_unix_bg ($cmd) {
// Executes $cmd in the background and returns the PID as an integer
return (int) exec("$cmd > /dev/null 2>&1 & echo $!");
}
function pid_exists ($pid) {
// Checks whether a process with ID $pid is running
// There is probably a better way to do this
return (bool) trim(exec("ps | grep \"^$pid \""));
}

$cmd = "/path/to/your/cpp arg_1 arg_2 arg_n";

// Start the C++ program
$pid = exec_unix_bg($cmd);

// Ignore user aborts to allow us to dispatch a signal to the child
ignore_user_abort(1);

// Loop until the program completes
while (pid_exists($pid)) {

// Push some harmless data to the client
echo " ";
flush();

// Check whether the client has disconnected
if (connection_aborted()) {
posix_kill($pid, SIGTERM); // Or SIGKILL, or whatever
exit;
}

// Could be done better? Only here to prevent runaway CPU
sleep(1);

}

// The process has finished. Do your thang here.

要收集程序的输出,将输出重定向到文件而不是 /dev/null。我怀疑您需要为此安装 pcntl 以及 posix,因为 PHP 手册指出 SIGxxx 常量由 定义pcntl 扩展 - 虽然我从来没有在没有安装另一个的情况下安装过一个,所以我不确定是哪种方式。

关于PHP - 在客户端断开连接时杀死 exec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11394159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com