Home > Software engineering >  Child process not killed - Node js ( inside Electron js app, windows)
Child process not killed - Node js ( inside Electron js app, windows)

Time:07-08

I am trying to stop this command after 4 seconds, but it doesn't stop the child-process (Running in an electron-js app, windows )

child = child_process.spawn("ping google.com -t", {
  encoding: 'utf8',
  shell: true
});

child.stdout.on('data', (data) => {
  //Here is the output
  data=data.toString();
  
  console.log(data)
});


setTimeout(function() {
  console.log('Killing Your child', child.pid);
  child.kill()
}, 4 * 1000);

the timeout runs after 4 seconds, it logs the message but never stops the process

I tried using tags inside the kill() like "SIGINT" or "SIGKILL"

I tried running without the timeout too...

CodePudding user response:

By looking at the official documentation for child process I have slightly modified your provided example to a bare minimum of what still seems to work for me. Please note that the ping -t flag requires an argument which you didn't provide.

The following worked for me (the program exits after 4 pings) on Node LTS (16.15.1) and the latest version (18.4.0):

const { spawn } = require('child_process');

const child = spawn("ping", ['www.google.com'], {});
child.stdout.on('data', (data) => { console.log(data.toString()); });

setTimeout(() => {
  console.log('Killing Your child', child.pid);
  child.kill();
}, 4000);

CodePudding user response:

shell: true doesn't work with .kill() as you can see in the answer from this post:

Try to kill a spawn process with shell true and detached true nodejs

I needed to replace:

child.kill() 

with

  child_process.spawn("taskkill", ["/pid", child.pid, '/f', '/t']);
  • Related