0

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) => {
// 
});
E_net4
  • 27,810
  • 13
  • 101
  • 139

2 Answers2

2

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?

Ryhazerus
  • 440
  • 3
  • 9
  • How do I get a process number? –  Sep 02 '21 at 23:47
  • 1
    If using ```spawn``` or ```exec``` you can find the pid by using the return value of the called function. ```const myProcess = spawn ( cmd , args , { cwd : path } ); myProcess.pid``` – Ryhazerus Sep 03 '21 at 06:59
0

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.