I am using forever-monitor on Windows where child processes are detached by default.
In my application I have a monitor.js
file which monitors a server.js
file and I want to be able to notify server.js
when I close my application by exiting monitor.js
(hitting Ctrl + C
on the command-line).
Here is my demo code:
monitor.js
const path = require('path');
const forever = require('forever-monitor');
let child;
function exit() {
console.error('Received exit signal on main process.');
if (child) {
// TODO: Here I want to notify the "child", so that it can gracefully shutdown my server
child.stop();
}
process.exit(0);
}
['SIGINT', 'SIGKILL', 'SIGTERM'].forEach(signal => process.on(signal, exit));
child = new forever.Monitor(path.join(__dirname, 'server.js'));
child.start();
server.js
const express = require('express');
const app = express();
const port = process.env.PORT || 8080;
let server;
function stopServer() {
if (server) {
console.log('Shutting down server...');
server.close();
}
}
app.get('/', (request, response) => response.send('Hello'));
server = app.listen(port, () => console.log(`Server is running on port "${port}".`));
How can I call stopServer
in server.js
when monitor.js
receives a SIGINT
?
The secret sauce is to start the child process with option "fork".
Using the "fork" option makes it possible to send messages from the parent process to the child process by calling
child.send
. This gives the ability to listen in the child process on a customclose
message from the parent process, so that the child can stop the server and exit with custom exit code1337
.When the parent/main process realizes that the child process has been closed with code
1337
, then the main process also shuts down.Here is my solution:
monitor.js
server.js