diff --git a/src/Core/GameProcessServer.php b/src/Core/GameProcessServer.php index b5c8b2a..0ff4861 100644 --- a/src/Core/GameProcessServer.php +++ b/src/Core/GameProcessServer.php @@ -181,11 +181,56 @@ class GameProcessServer implements MessageComponentInterface */ private function readProcessOutput(ConnectionInterface $conn): void { - $process = $this->processes[$conn->resourceId] ?? null; + $connId = $conn->resourceId; + $process = $this->processes[$connId] ?? null; if (!$process) { return; } + // 检查进程是否还在运行 + $processStatus = proc_get_status($process['process']); + if ($processStatus && !$processStatus['running']) { + // 进程已经退出,读取最后的输出并关闭连接 + echo "[进程] 进程 {$connId} 已退出,状态码: " . $processStatus['exitcode'] . "\n"; + + // 尝试读取任何剩余的输出 + $finalOutput = ''; + $bufferSize = 8192; + + while (true) { + $chunk = @fread($process['stdout'], $bufferSize); + if ($chunk === '' || $chunk === false) { + break; + } + $finalOutput .= $chunk; + } + + while (true) { + $chunk = @fread($process['stderr'], $bufferSize); + if ($chunk === '' || $chunk === false) { + break; + } + $finalOutput .= $chunk; + } + + if ($finalOutput) { + $this->sendMessage($conn, [ + 'type' => 'output', + 'text' => $finalOutput + ]); + } + + // 发送进程退出消息 + $this->sendMessage($conn, [ + 'type' => 'system', + 'message' => '游戏进程已退出' + ]); + + // 关闭连接 + $conn->close(); + return; + } + $output = ''; // 在非阻塞模式下,使用fread读取可用数据