user11287402
user11287402

Reputation:

How do I kill a child process

Is there a way to kill a child process started using exec? Believe it or not, not all applications just end (such as ls) but continue unless you exit them using the control-c shortcut. Is there a way to replicate this via code. I want to kill the process. Here is some code that initializes the process, if that helps.

const notcp = require("child_process");
notcp.exec("./IAmAnAppThatDoesntJustStop.sh", (error, stdout, stderr) => {
// 
});

Upvotes: 0

Views: 2178

Answers (2)

Merunas Grincalaitis
Merunas Grincalaitis

Reputation: 859

The ONLY thing that has worked for me to kill an .exec() child process is to use the npm library terminate after trying every single signal with kill none of them worked. But terminate did. Here's how:

const terminate = require('terminate')
terminate(myProcess.pid, err => console.log(err))

Where myProcess is simply this: const myProcess = childProcess.exec(...). You don't need to use { detached: true } on the child process, it's not necessary.

You can install terminate with: yarn add terminate (it's not my project)

This worked perfectly.

Upvotes: 0

Ryhazerus
Ryhazerus

Reputation: 510

If you're dead set on using .exec() to execute your script then, no there is no (easy) built-in way to end the processes you just started. If you're flexible and can use the .spawn() function instead, things change and you checkout the following question/answer on Stackoverflow.

If you still want to use .exec() maybe try using a library such as Taskkill or Fkill to simplify the complexity of implementing such a feature?

Upvotes: 2

Related Questions