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

时间:2018-10-23 20:49:37

标签: node.js child-process spawn

是否有一种方法可以确定所有生成的子进程何时关闭或退出?

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

_id

1 个答案:

答案 0 :(得分:0)

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

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 event来减少计数器(而不是close),因为exit是在进程终止时触发的,而close是在stdio流关闭时触发的。