Skip to content

Instantly share code, notes, and snippets.

@lenconda
Created February 13, 2022 15:06
Show Gist options
  • Save lenconda/fd6d2773ca1cedd5bd7b7ab80197e71e to your computer and use it in GitHub Desktop.
Save lenconda/fd6d2773ca1cedd5bd7b7ab80197e71e to your computer and use it in GitHub Desktop.
Daemonize & keep alive
const child_process = require('child_process');
const daemon = (pathname) => {
const child = child_process.fork(pathname);
child.unref();
return child;
};
module.exports = daemon;
const cluster = require('cluster');
const _ = require('lodash');
const keepalive = async (cb) => {
if (cluster.isMaster) {
cluster.fork();
cluster.on('exit', () => {
cluster.fork();
});
}
if (cluster.isWorker && _.isFunction(cb)) {
await cb();
}
};
module.exports = keepalive;
const daemon = require('./daemon');
const path = require('path');
const child = daemon(path.resolve(__dirname, './test.service.js'));
console.log(child.pid);
process.exit();
const keepalive = require('./keepalive');
const fs = require('fs');
const path = require('path');
keepalive(async () => {
const logFilePathname = path.resolve(__dirname, './info.log');
fs.appendFileSync(logFilePathname, 'new process\n', { encoding: 'utf-8' });
for (let i = 0; i < 10; i += 1) {
fs.appendFileSync(logFilePathname, new Date().toISOString() + '\n', { encoding: 'utf-8' });
await new Promise((resolve) => setTimeout(() => resolve(), 500));
}
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment