如何终止命令行进程从 child_process nodejs 开始

how to kill command line process start with child_process nodejs

我怎么能停止它,它在我停止 nodejs 后保持 运行。我尝试 process.kill() 但没有用

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

在阅读了几个小时的 nodejs 文档后,我为遇到同样问题的人找到了这篇文章

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

我修改了你的代码如下以清除错误:

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

ping 命令在 -t 后需要一个参数(根据终端:ping: option requires an argument -- t