【发布时间】:2019-04-08 05:20:53
【问题描述】:
我正在尝试使用 child_process.spawn 在 for 循环中调用 CLI 工具,每次调用时使用不同的参数。到目前为止一切都很好,但是如果我想引入最大数量的子进程并且只在前一个进程关闭时继续生成新进程,我就会遇到麻烦。当达到有限的子进程数量时,我想用无限的while循环停止for循环。但是,子进程似乎从不触发“关闭”事件。
以ls 为例(抱歉,我想不出一个长时间自动退出的好命令):
const { spawn } = require("child_process");
const max = 3;
let current = 0;
// dirsToVisit is an array of paths
for (let i = 0; i < dirsToVisit.length; i++) {
// if already running 3 ls, wait till one closes
while (current >= max) {}
current++;
lsCommand(dirsToVisit[i]);
}
function lsCommand(dir) {
const ls = spawn("ls", [dir]);
ls.on("close", code => {
current--;
console.log(`Finished with code ${code}`);
});
}
上面的代码永远不会退出,当子进程退出时要在控制台中记录的字符串永远不会打印在屏幕上。如果我删除 while 循环,所有子进程最终都会顺利完成,但同时允许的进程数没有限制。
为什么我的代码不工作,如何正确限制循环中产生的子进程的数量?任何帮助将不胜感激!
【问题讨论】:
标签: javascript node.js concurrency child-process