From 8b4928c833388040a49b906d6e82e83ce7f8f18c Mon Sep 17 00:00:00 2001 From: Nazar Hussain Date: Mon, 5 Feb 2024 12:24:17 +0100 Subject: [PATCH] Update stopChildProcess --- packages/test-utils/src/childProcess.ts | 26 +++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/packages/test-utils/src/childProcess.ts b/packages/test-utils/src/childProcess.ts index 35149b1ca967..c3cacb9a1509 100644 --- a/packages/test-utils/src/childProcess.ts +++ b/packages/test-utils/src/childProcess.ts @@ -79,6 +79,19 @@ export async function execChildProcess(cmd: string | string[], options?: ExecChi }); } +/** + * Check if process with given pid is running + */ +export function isPidRunning(pid: number): boolean { + try { + // Signal 0 is a special signal that checks if the process exists + process.kill(pid, 0); + return true; + } catch { + return false; + } +} + export const stopChildProcess = async ( childProcess: childProcess.ChildProcess, signal: NodeJS.Signals | number = "SIGTERM" @@ -87,11 +100,20 @@ export const stopChildProcess = async ( return; } - return new Promise((resolve, reject) => { + const pid = childProcess.pid; + + await new Promise((resolve, reject) => { childProcess.once("error", reject); - childProcess.once("close", resolve); + // We use `exit` instead of `close` as multiple processes can share same `stdio` + childProcess.once("exit", resolve); childProcess.kill(signal); }); + + if (pid != null && isPidRunning(pid)) { + // Wait for sometime and try to kill this time + await sleep(500); + await stopChildProcess(childProcess, "SIGKILL"); + } }; /**