节点 child_process.spawn:确定所有生成的子进程何时关闭或退出?



有没有办法确定所有生成的子进程何时关闭或退出?

例如,如何确定没有更多进程要运行,或者换句话说,我的 500 个子进程都已退出?

for (let index = 0; index < 500; index++) {
wkhtmltopdf = spawn('/usr/local/bin/wkhtmltopdf', ['--margin-left', '0', `${index}.html`, `${index}.pdf`])
wkhtmltopdf.stdout.on('data', (data) => {
console.log(`stdout: ${data}`)
})
wkhtmltopdf.stderr.on('data', (data) => {
console.log(`stderr: ${data}`)
})
wkhtmltopdf.on('close', (code) => {
console.log(`child process exited with code ${code}`)
})
}

您需要做的就是保留一个计数器,并在子进程终止时递减它。

var num_proc = 500;
var counter = num_proc;
for (let index = 0; index < num_proc; index++) {
wkhtmltopdf = spawn('/usr/local/bin/wkhtmltopdf', 
['--margin-left', '0', `${index}.html`, `${index}.pdf`]);
wkhtmltopdf.stdout.on('data', (data) => {
console.log(`stdout: ${data}`)
})
wkhtmltopdf.stderr.on('data', (data) => {
console.log(`stderr: ${data}`)
})
wkhtmltopdf.on('close', (code) => {
console.log(`child process stdio terminated with code ${code}`)
})
wkhtmltopdf.on('exit', (code) => {
console.log(`child process exited with code ${code}`)
counter--;
if (counter <= 0) {
console.log('everything finished')
}
})
}

我会使用 exit 事件来递减计数器(而不是close(,因为exit是在进程终止时触发的,而close是在 stdio 流关闭时触发的。

最新更新