Node.js 检测子进程退出

标签 node.js exit child-process

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

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

最佳答案

查看 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);

关于Node.js 检测子进程退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34881343/

相关文章:

java - 中断类Main,如果该方法返回 "false"

javascript - 为什么在创建对象之前使用 global.gc() 可以防止堆使用量出现负增量?

node.js - NodeJS 的子进程 args 数组是否清理参数?

javascript - 使用 javascript get 查询循环进入一个空数组

node.js - 网络实时分析仪表板 : which technologies should use?( Node/django、cassandra/mongodb ...)

函数指针的 Javascript module.export 结构

用于数据保存的 Node.js 压缩代理

Maven - Mercurial/Svn - svn/hg 标记失败,退出代码为 255

c++ - "Safely"在按键时终止正在运行的 C++ 程序?

javascript - NodeJS : child_process. exec 未执行函数