Node.js检测子进程退出

时间:2016-01-19 16:00:10

标签: node.js exit child-process

我在node中工作,因为它通过visual studio代码扩展发生。我成功创建子进程,并可以命令终止它们。我希望在进程意外退出时运行代码,这似乎是"退出"事件是打算的,但是我不知道如何调用它,这是我正在使用的代码,进程运行,但是没有检测/登录退出,请注意output.append是visual studio代码特定的console.log()的版本:

        child = exec('mycommand', {cwd: path}, 
        function (error, stdout, stderr) { 
            output.append('stdout: ' + stdout);
            output.append('stderr: ' + stderr);
            if (error !== null) {
                output.append('exec error: ' + error);
            }
        });

        child.stdout.on('data', function(data) {
            output.append(data.toString()); 
        });

以下我试过的四件事在登录退出时无效:

        child.process.on('exit', function(code) {
            output.append("Detected Crash");
        });

        child.on('exit', function(code) {
            output.append("Detected Crash");
        });

        child.stdout.on('exit', function () {
            output.append("Detected Crash");
        });

        child.stderr.on('exit', function () {
            output.append("Detected Crash");
        });

1 个答案:

答案 0 :(得分:6)

查看node.js source code for the child process module.exec()方法本身就是这样做的:

child.addListener('close', exithandler);
child.addListener('error', errorhandler);

而且,我认为.on().addListener()的快捷方式,所以您也可以这样做:

child.on('close', exithandler);
child.on('error', errorhandler);
相关问题