/** * 服务守护脚本。当服务器进程失败时,重启IM服务器。 * * 守护服务不是应用程序的入口,但作为服务的外壳,提供进程信号监听与进程重启,保证服务的连续性。 */ "use strict"; let cp = require('child_process'); let worker; require('util'); function startWorker(spawnScript) { // 进程守护,开启IPC通道双向通信 let exeFile = process.platform === "linux" ? "./node" : "node"; worker = cp.spawn(exeFile, [spawnScript], {stdio: [0, 1, 2, 'ipc']}); //监视子进程,当其崩溃时重启服务 worker.on('exit', function (code) { if (code !== 0) { console.log('IM server is down, restarting...'); startWorker(spawnScript); } }); worker.on('message', function (msg) { console.log(msg); }); } function main() { console.log('Armour process id: ' + process.pid); startWorker('./app.js'); // 守护进程本身退出时,关闭其启动的服务 process.on('SIGTERM', function () { worker.kill(); process.exit(0); }); } main();