Killing process families with node

Almenon
2 min readApr 7, 2018

Killing a solitary process with node is very simple.

import { spawn, ChildProcess } from "child_process"
child = spawn("command", ["argument"])
child.kill()

This will ask nicely for the child to kill itself by sending a SIGTERM signal. The child will have a chance to clean up before it commits seppuku.

But let’s say you are not in a nice mood. You can murder a process immediately with SIGKILL.

child.kill('SIGKILL')

In most cases SIGKILL will suffice. But let’s say you are really angry. You are a WRATHFUL GOD who wants to ERADICATE the entire process family.

Now it gets a bit complicated. Node does not actually support this on windows.

Fortunately Krasimir has good multi-platform solution.

I did the same thing in Typescript, with a slight twist:

On linux if you spawn the process in a detached state you can simply kill the group by passing in a negative process identifier.

child = spawn("command", ["argument"], {'detached':true});
process.kill(-child.pid)

So the final code ends up being:

A real-world example of this can be seen in my birdseye-vscode extension:

Upon launch of birdseye you will notice two python processes:

you can get command line column in windows task explorer by right clicking on the header row and clicking on select columns

The extension used to just kill the parent process (25156), as I didn’t even know the child process existed. The poor child would be left alone, orphaned.

After some investigation I arrived at the solution described above. Now when birdseye exits the entire family is sent to sleep with the fishes. 🐟

For more reading: the official node documentation on process and child process

--

--