Node.js:启动后分离一个进程

问题描述 投票:2回答:1

我以这种方式启动Node.js子进程:

let process = spawn(apiPath, {
  detached: true
})

process.unref()

process.stdout.on('data', data => { /* do something */ })

开始该过程时,我需要保持其附件状态,因为我想读取其输出。但是在关闭我的Node进程(父进程)之前,我想分离所有未完成的子进程以使其在后台运行,但是正如the documentation所说的:

[当使用分离选项启动长时间运行的进程时,除非父进程没有提供未连接到父进程的stdio配置,否则该进程将在父进程退出后不会在后台继续运行。

但是使用选项stdio: 'ignore',我无法读取stdout,这是一个问题。

我试图在关闭父进程之前手动关闭管道,但未成功:

// Trigger just before the main process end
process.stdin.end()
process.stderr.unpipe()
process.stdout.unpipe()
node.js multithreading spawn
1个回答
0
投票

您的问题非常有趣,因此我花了一些时间来重述您希望实现的目标的最小工作示例,该示例基本上是从我所了解的是拥有一个可以读取子进程的stdin的父进程以及何时父母退出孩子继续在后台运行,所以这就是我的实现方式。基本上,您需要在初始化时将父级的stdin传递给子级。这是我的最小示例。

这是父代码:

  const { spawn } = require('child_process')
  const opts = {
        detached: true,
        stdio: [process.stdin, 'ignore', 'ignore', 'pipe']
       }
  let child = spawn('node', ['child.js'], opts)

  process.stdout.on("data", function(data) {
        console.log(data)
   })

这是子代码:

  setInterval(function() {

     process.stdin.write('hello from child')

  }, 1000)
© www.soinside.com 2019 - 2024. All rights reserved.