简体   繁体   中英

Child process not killed - Node js ( inside Electron js app, windows)

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

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);

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']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM