From 2a866988f91c253caa082b89188d2a243f2744bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E6=98=9F=E8=99=8E?= <105782492+xingxinag@users.noreply.github.com> Date: Sat, 27 Sep 2025 17:59:02 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=A3=E5=86=B3=20win11=20=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E5=88=A4=E6=96=AD=E6=9C=8D=E5=8A=A1=E6=9C=AA=E8=BF=90=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修改 isServiceRunning 函数, 使用 tasklist 命令 --- src/utils/processCheck.ts | 47 +++++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/src/utils/processCheck.ts b/src/utils/processCheck.ts index 1c9eed3..9e106ae 100644 --- a/src/utils/processCheck.ts +++ b/src/utils/processCheck.ts @@ -2,6 +2,7 @@ import { existsSync, readFileSync, writeFileSync } from 'fs'; import { PID_FILE, REFERENCE_COUNT_FILE } from '../constants'; import { readConfigFile } from '.'; import find from 'find-process'; +import { execSync } from 'child_process'; // 引入 execSync 来执行命令行 export async function isProcessRunning(pid: number): Promise { try { @@ -37,16 +38,54 @@ export function getReferenceCount(): number { return parseInt(readFileSync(REFERENCE_COUNT_FILE, 'utf-8')) || 0; } -export async function isServiceRunning(): Promise { +export function isServiceRunning(): boolean { if (!existsSync(PID_FILE)) { return false; } + let pid: number; try { - const pid = parseInt(readFileSync(PID_FILE, 'utf-8')); - return await isProcessRunning(pid); + const pidStr = readFileSync(PID_FILE, 'utf-8'); + pid = parseInt(pidStr, 10); + if (isNaN(pid)) { + // PID 文件内容无效 + cleanupPidFile(); + return false; + } } catch (e) { - // Process not running, clean up pid file + // 读取文件失败 + return false; + } + + try { + if (process.platform === 'win32') { + // --- Windows 平台逻辑 --- + // 使用 tasklist 命令并通过 PID 过滤器查找进程 + // stdio: 'pipe' 压制命令的输出,防止其显示在控制台 + const command = `tasklist /FI "PID eq ${pid}"`; + const output = execSync(command, { stdio: 'pipe' }).toString(); + + // 如果输出中包含了 PID,说明进程存在 + // tasklist 找不到进程时会返回 "INFO: No tasks are running..." + // 所以一个简单的包含检查就足够了 + if (output.includes(pid.toString())) { + return true; + } else { + // 理论上如果 tasklist 成功执行但没找到,这里不会被命中 + // 但作为保险,我们仍然认为进程不存在 + cleanupPidFile(); + return false; + } + + } else { + // --- Linux, macOS 等其他平台逻辑 --- + // 使用信号 0 来检查进程是否存在,这不会真的杀死进程 + process.kill(pid, 0); + return true; // 如果没有抛出异常,说明进程存在 + } + } catch (e) { + // 捕获到异常,说明进程不存在 (无论是 kill 还是 execSync 失败) + // 清理掉无效的 PID 文件 cleanupPidFile(); return false; }