From 3e02114ef37dfdaa2c0df1acb140d5ae120272a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leo=20Wang=28=E8=8D=89=E9=9E=8B=E6=B2=A1=E5=8F=B7=29?= <308487730@qq.com> Date: Fri, 20 Sep 2024 17:39:59 +0800 Subject: [PATCH] fix: better tree kill logic #251 --- src/index.ts | 21 +++++++++++++++++---- src/utils.ts | 12 ++++-------- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/src/index.ts b/src/index.ts index 72b56a6..09f249b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,7 +8,9 @@ import { resolveServerUrl, resolveViteConfig, withExternalBuiltins, - treeKillSync, + killTreeWin32, + killTree, + pidTree, } from './utils' // public utils @@ -167,10 +169,21 @@ export async function startup( startup.hookedProcessExit = false startup.exit = async () => { if (process.electronApp) { - await new Promise((resolve) => { + const isWin32 = process.platform === 'win32' + const pid = process.electronApp.pid! + const tree = isWin32 ? null : pidTree({ pid, ppid: process.pid }) + + await new Promise((resolve) => { process.electronApp.removeAllListeners() - process.electronApp.once('exit', resolve) - treeKillSync(process.electronApp.pid!) + process.electronApp.once('exit', () => { + if (isWin32) { + killTreeWin32(pid) + } else { + killTree(tree!) + } + resolve() + }) + process.kill(pid) }) } } diff --git a/src/utils.ts b/src/utils.ts index 2776938..7ef6a29 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -141,15 +141,11 @@ export function resolvePackageJson(root = process.cwd()): { * Inspired `tree-kill`, implemented based on sync-api. #168 * @see https://github.com/pkrumins/node-tree-kill/blob/v1.2.2/index.js */ -export function treeKillSync(pid: number) { - if (process.platform === 'win32') { - cp.execSync(`taskkill /pid ${pid} /T /F`) - } else { - killTree(pidTree({ pid, ppid: process.pid })) - } +export function killTreeWin32(pid: number) { + cp.execSync(`taskkill /pid ${pid} /T /F`) } -function pidTree(tree: PidTree) { +export function pidTree(tree: PidTree) { const command = process.platform === 'darwin' ? `pgrep -P ${tree.pid}` // Mac : `ps -o pid --no-headers --ppid ${tree.ppid}` // Linux @@ -168,7 +164,7 @@ function pidTree(tree: PidTree) { return tree } -function killTree(tree: PidTree) { +export function killTree(tree: PidTree) { if (tree.children) { for (const child of tree.children) { killTree(child)