Pervez
Pervez

Reputation: 431

How to kill a NodeJS child exec process?

I'm executing a Python program from NodeJS using exec function of child_process and I wish to kill the process on a button click. Am using Windows11.

Here is my code :

var process__ = undefined; // this is a global variable

    function executePython(command_line_arguement){
      const exec = require('child_process').exec;
      process__=exec(`python program.py "${command_line_arguement}"`, { encoding: 'utf-8',detached : true }, (error, stdout, stderr) => {
        if (error) {
          console.error(`exec error: ${error}, ${stderr}`);
        }else{
        console.log(stdout);
        }
      });

    function onButtonClick(){
        process__.kill('SIGINT');
    }

However, this doesn't seem to halt or kill the python process that was triggered.

Any guidance on how to proceed would be appreciable.

Thanks in advance !!

Upvotes: 1

Views: 1625

Answers (1)

NoCommandLine
NoCommandLine

Reputation: 6323

I believe windows needs a force kill to terminate the process i.e. something like

exec('taskkill /F /T /PID ' + process__.pid);

// F - force terminate
// T - kill all sub-processes
// PID - Process Id that you're targetting

See documentation for taskkill and the flags

Upvotes: 2

Related Questions