Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: better tree kill logic #251 #253

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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