如何通过永久监视父进程中的SIGINT来通知子进程?

时间:2018-05-10 12:21:44

标签: node.js process forever sigint forever-monitor

我在Windows上使用forever-monitor默认情况下child processes are detached

在我的应用程序中,我有一个monitor.js文件,用于监控server.js文件,我希望能够在退出server.js时关闭应用程序时通知monitor.js(在命令行上点击Ctrl + C

这是我的演示代码:

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}".`));

stopServer收到server.js时,如何在monitor.js中致电SIGINT

1 个答案:

答案 0 :(得分:2)

秘诀就是用选项" fork"来启动子进程。

使用" fork"选项可以通过调用child.send将消息从父进程发送到子进程。这使得能够在父进程的自定义close消息中侦听子进程,以便子进程可以停止服务器并使用自定义退出代码1337退出。

当父/主进程意识到子进程已使用代码1337关闭时,主进程也会关闭。

这是我的解决方案:

<强> monitor.js

const path = require('path');
const forever = require('forever-monitor');

let child;

function exit(signal) {
  console.error(`Received "${signal}" signal on main process.`);
  if (child) {
    child.send({action: 'close'});
  }
}

['SIGINT', 'SIGKILL', 'SIGTERM'].forEach(signal => process.on(signal, () => exit(signal)));

process.on('exit', (code) => console.log(`Stopped main process with code "${code}".`));

const options = {fork: true};

child = new forever.Monitor(path.join(__dirname, 'server.js'), options);

child.on('exit:code', (code) => {
  if (code === 1337) {
    if (child) {
      child.stop();
      console.log('Successfully stopped child process.');
    }
    console.log('Stopping main process ...');
    process.exit(0);
  }
});

child.start();

<强> server.js

const express = require('express');

const app = express();
const port = process.env.PORT || 8080;

let server;

if (process.send) {
  process.on('message', function (message) {
    console.log(`Received "${message.action}" message from main process.`);
    if (message.action === 'close') {
      stopServer();
    }
  });
}

function stopServer() {
  if (server) {
    console.log('Stopping server in child process ...');
    server.close(() => {
      console.log('Stopped server in child process.');
      process.exit(1337);
    });
  }
}

app.get('/', (request, response) => response.send('Hello'));
server = app.listen(port, () => console.log(`Server is running on port "${port}".`));