解决 win11 错误判断服务未运行

修改 isServiceRunning 函数, 使用 tasklist 命令
This commit is contained in:
小星虎
2025-09-27 17:59:02 +08:00
committed by GitHub
parent 1028f7582e
commit 2a866988f9

View File

@@ -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<boolean> {
try {
@@ -37,16 +38,54 @@ export function getReferenceCount(): number {
return parseInt(readFileSync(REFERENCE_COUNT_FILE, 'utf-8')) || 0;
}
export async function isServiceRunning(): Promise<boolean> {
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;
}