vy.pham
vy.pham

Reputation: 611

how to kill command line process start with child_process nodejs

how can i stop it, it keep running after i stop nodejs. I try process.kill() but not working

const process = require('child_process')
const child = process.exec('ping 8.8.8.8 -t')
setTimeout(()=>child.kill(2),10000)

after a few hour reading nodejs docs, i found this for who have same my problem

const process = require('child_process')
const child = process.execFile('ping 8.8.8.8',['-t'],{cwd:'your working direct'})
setTimeout(()=>child.kill(2),10000)//now kill() working

Upvotes: 1

Views: 577

Answers (1)

elight
elight

Reputation: 562

I modified your code as below to flush out the error:

const process = require('child_process')
const child = process.spawn('ping 8.8.8.8 -t') // instead of process.exec
setTimeout(() => {
    console.log(child.kill(2)) // --> false == failed
}, 10000);

child.on('error', (code, signal) => {
    console.log(`${code}`) // --> Error: spawn ping 8.8.8.8 -t ENOENT
});

The ping command requires an argument after the -t ( as per terminal: ping: option requires an argument -- t

Upvotes: 3

Related Questions