V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
WildCat
V2EX  ›  Node.js

求个 child_process 自动重启(crash 不会引起主进程退出,并自动重启)的代码示例

  •  
  •   WildCat · 2014-05-26 22:25:29 +08:00 · 2786 次点击
    这是一个创建于 3593 天前的主题,其中的信息可能已经有所发展或是发生改变。
    7 条回复    2014-06-19 09:42:00 +08:00
    heiher
        1
    heiher  
       2014-05-27 07:16:32 +08:00 via iPhone
    #!/bin/bash

    while true; do
    # run your app in foreground
    done
    WildCat
        2
    WildCat  
    OP
       2014-05-27 07:21:35 +08:00 via iPhone
    @heiher 抱歉,BAE环境,只能纯node实现
    rekey
        3
    rekey  
       2014-05-27 15:00:07 +08:00
    代码运行在
    try{}catch(e){}
    里试试?
    withinthefog
        4
    withinthefog  
       2014-05-27 18:07:47 +08:00
    WildCat
        5
    WildCat  
    OP
       2014-05-27 18:09:07 +08:00
    @withinthefog BAE环境 似乎不能用这个。
    withinthefog
        6
    withinthefog  
       2014-05-28 10:13:11 +08:00   ❤️ 1
    cluster.on('exit', function(worker, code, signal) {
    console.log('worker %d died (%s). restarting...',
    worker.process.pid, signal || code);
    cluster.fork();
    });

    要纯手写的话大概就是这个样子了,不知道你的child_process是不是用cluster模块手工创建的
    可以参考node.js官方的cluster模块文档:
    http://nodejs.org/api/cluster.html#cluster_cluster
    Honwhy
        7
    Honwhy  
       2014-06-19 09:42:00 +08:00   ❤️ 1
    楼主你需要的是这个么?
    ```
    var cp = require('child_process');

    var worker;

    function spawn(server, config) {
    worker = cp.spawn('node', [ server, config ]);
    worker.on('exit', function (code) {
    if (code !== 0) {
    spawn(server, config);
    }
    });
    }

    function main(argv) {
    spawn('server.js', argv[0]);
    process.on('SIGTERM', function () {
    worker.kill();
    process.exit(0);
    });
    }

    main(process.argv.slice(2));
    ```
    [七天学会NodeJS](http://nqdeng.github.io/7-days-nodejs/)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3357 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 13:41 · PVG 21:41 · LAX 06:41 · JFK 09:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.