Skip to content

Commit

Permalink
fix: better tree kill logic #251
Browse files Browse the repository at this point in the history
  • Loading branch information
caoxiemeihao committed Sep 20, 2024
1 parent 4aae557 commit 3e02114
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 12 deletions.
21 changes: 17 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import {
resolveServerUrl,
resolveViteConfig,
withExternalBuiltins,
treeKillSync,
killTreeWin32,
killTree,
pidTree,
} from './utils'

// public utils
Expand Down Expand Up @@ -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<void>((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)
})
}
}
12 changes: 4 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down

0 comments on commit 3e02114

Please sign in to comment.