mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-28 11:20:22 +08:00
fix: 回收流程防 PID 复用误杀并等待端口释放,版本 1.1.86(#197/#198)
合并 #197/#198 后加固:记录 pid 命令行不可读时必须在监听端口上才杀;杀不掉保留记录下次重试;taskkill 后等待进程退出再绑端口。桌面换包顺序与失败兜底随 PR #198 一并发布。
This commit is contained in:
1 parent
52d3b2a2f2
commit
1bdf239970
5 files changed
+117
-14
No files matched your search
@@ -85,19 +85,31 @@ function main() {
|
||||
|
||||
try {
|
||||
let killed = 0;
|
||||
const killedPids = [];
|
||||
let rec = null;
|
||||
try {
|
||||
rec = JSON.parse(fs.readFileSync(record, "utf8"));
|
||||
} catch {
|
||||
rec = null;
|
||||
}
|
||||
if (rec && rec.pid && alive(rec.pid)) {
|
||||
const cmd = cmdlineOf(rec.pid);
|
||||
if (!cmd || isDshWeb(cmd)) {
|
||||
if (kill(rec.pid)) killed += 1;
|
||||
const listeners = listeningPids(port);
|
||||
const recPid = Number(rec && rec.pid) || 0;
|
||||
let recStillAlive = false;
|
||||
if (recPid && alive(recPid)) {
|
||||
const cmd = cmdlineOf(recPid);
|
||||
// 命令行拿不到时,必须证明这个 pid 仍占着端口才杀:记录可能早于进程退出,
|
||||
// pid 被系统复用后盲目 taskkill 会杀掉无关进程。
|
||||
const ownsPort = listeners.includes(recPid);
|
||||
if (isDshWeb(cmd) || (!cmd && ownsPort)) {
|
||||
if (kill(recPid)) {
|
||||
killed += 1;
|
||||
killedPids.push(recPid);
|
||||
}
|
||||
}
|
||||
recStillAlive = alive(recPid);
|
||||
}
|
||||
if (rec) {
|
||||
// 杀不掉就留着记录,下一次启动再试;只有确认进程已经不在才清记录。
|
||||
if (rec && !recStillAlive) {
|
||||
try {
|
||||
fs.unlinkSync(record);
|
||||
} catch {
|
||||
@@ -106,13 +118,20 @@ function main() {
|
||||
}
|
||||
|
||||
if (!killed) {
|
||||
for (const pid of listeningPids(port)) {
|
||||
for (const pid of listeners) {
|
||||
if (pid === process.pid) continue;
|
||||
if (!isDshWeb(cmdlineOf(pid))) continue;
|
||||
if (kill(pid)) killed += 1;
|
||||
if (kill(pid)) {
|
||||
killed += 1;
|
||||
killedPids.push(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// taskkill 返回不代表端口已经释放。等被杀进程真正退出再让 Cordis 绑端口,
|
||||
// 否则还是会撞 EADDRINUSE。
|
||||
waitGone(killedPids);
|
||||
|
||||
if (killed) {
|
||||
process.stderr.write(`[dsh-purge] reclaimed stale dsh web on :${port}, retrying boot\n`);
|
||||
}
|
||||
@@ -121,4 +140,17 @@ function main() {
|
||||
}
|
||||
}
|
||||
|
||||
function waitGone(pids, timeoutMs = 1500) {
|
||||
if (!pids.length) return;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const sleeper = new Int32Array(new SharedArrayBuffer(4));
|
||||
while (Date.now() < deadline && pids.some((pid) => alive(pid))) {
|
||||
try {
|
||||
Atomics.wait(sleeper, 0, 0, 80);
|
||||
} catch {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
Reference in new issue
Block a user