Friday, July 22, 2022

[FIXED] How to kill a NodeJS child exec process?

Issue

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 !!


Solution

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



Answered By - NoCommandLine
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.