node.js - 启动后分离一个 spawn 子进程

标签 node.js multithreading spawn

我以这种方式启动一个 spawn 子进程:

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

process.unref()

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

当我开始这个过程时,我需要保持它的连接,因为我想读取它的输出。但就在关闭我的 Node 进程(父进程)之前,我想分离所有未完成的子进程以保持它们在后台运行,但作为 the documentation说:

When using the detached option to start a long-running process, the process will not stay running in the background after the parent exits unless it is provided with a stdio configuration that is not connected to the parent.



但是使用选项 stdio: 'ignore'我看不懂 stdout这是一个问题。

我试图在关闭父进程之前手动关闭管道,但没有成功:
// Trigger just before the main process end
process.stdin.end()
process.stderr.unpipe()
process.stdout.unpipe()

最佳答案

经过多次测试,我找到了至少一种解决此问题的方法:在离开主进程之前销毁所有管道。

一个棘手的问题是子进程必须正确处理管道破坏,否则它可能会出错并关闭。在这个例子中, Node 子进程似乎没有问题,但它可能与其他场景不同。

主文件

const { spawn } = require('child_process')

console.log('Start Main')

let child = spawn('node', ['child.js'], { detached: true })
child.unref() // With this the main process end after fully disconnect the child

child.stdout.on('data', data => {
  console.log(`Got data : ${data}`)
})

// In real case should be triggered just before the end of the main process
setTimeout(() => {
  console.log('Disconnect the child')

  child.stderr.unpipe()
  child.stderr.destroy()
  child.stdout.unpipe()
  child.stdout.destroy()
  child.stdin.end()
  child.stdin.destroy()
}, 5000)

child .js
console.log('Start Child')

setInterval(function() {
   process.stdout.write('hello from child')
}, 1000)

输出

Start Main
Got data : Start Child

Got data : hello from child
Got data : hello from child
Got data : hello from child
Got data : hello from child
Disconnect the child

关于node.js - 启动后分离一个 spawn 子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59646654/

相关文章:

C# 检测生成的进程

javascript - 使用 mocha 模拟 Nodejs 中的函数

Cocoa 核心数据 - 后台线程

node.js - 如何使用 Twilio 发送短信,并等待手机响应以完成 NodeJS 中的请求

iphone - 推荐用于iPhone开发的线程层?

c++ - Qt:调用 QEventLoop::exec 后死锁

javascript - node.js child_process spawn stdout 降低 highWaterMark

node.js - Node : append output to existing file

javascript - 我使用 Express 中间件收到 UnhandledPromiseRejection

node.js - 当用户处于事件状态时,req.session.user 被删除