我以这种方式启动一个 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 ChildGot 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/