因此,我一直在尝试了解 Node 集群的工作原理,并且我有以下代码:
const cluster = require('cluster')
const os = require('os')
const express = require('express')
const app = express()
let cpus
// Check to see if the master process is running this
if (cluster.isMaster) {
console.log(`Master Process: ${process.pid} is running.`)
// Get the number of CPU's and fork that many workers
cpus = os.cpus().length
for(let i = 0; i < cpus; i++) {
console.log(`Forking process #${i+1}`)
cluster.fork()
}
// If worker process is killed log it
cluster.on('exit', (worker) => {
console.log(`Worker ${worker.process.pid} died.`)
})
// Once a worker is connected output they are online
cluster.on('online', (worker) => {
console.log(`Worker ${worker.process.pid} is online.`)
})
process.on('SIGINT', () => {
for(const id in cluster.workers) {
cluster.workers[id].kill('SIGINT')
}
})
} else {
// Each worker should listen on port 3000
app.listen(3000)
}
当我运行它然后退出时,Ctrl+C
我收到了这个控制台输出,我的主进程也死了。
Master Process: 19988 is running.
Forking process #1
Forking process #2
Forking process #3
Forking process #4
Worker 14684 is online.
Worker 14672 is online.
Worker 12520 is online.
Worker 3276 is online.
Worker 3276 died.
Worker 12520 died.
Worker 14672 died.
Worker 14684 died.
所以它正在做我想做的事情,但是当我SIGINT
所要做的就是杀死工人时,为什么主进程也会死?