Skip to content

Instantly share code, notes, and snippets.

@progress44
Forked from vinzdef/index.js
Created August 6, 2019 12:33
Show Gist options
  • Save progress44/c8eb030667e45c2198407c72058cec26 to your computer and use it in GitHub Desktop.
Save progress44/c8eb030667e45c2198407c72058cec26 to your computer and use it in GitHub Desktop.
Fork Process in Cluster
const server = require('./server.js')
const numCPUs = require('os').cpus().length
const cluster = require('cluster')
function makeCluster() {
return new Promise((resolve, reject) => {
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i++) {
cluster.fork()
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`)
})
resolve()
} else {
console.log(`Fork ${cluster.worker.id} is spawning`)
server.spawn()
.then(resolve)
.catch(reject)
}
})
}
makeCluster()
.then(_ => {
console.log('Child spawned')
})
.catch(e => {
console.log(`Fork failed: ${e}`)
})
module.exports = {
spawn: function() {
return new Promise(res => {
console.log('[!!!!] Spawned process')
res()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment