Node.js检测子进程退出

时间:2023-01-22 21:21:14

I am working in node, as it happens via a visual studio code extension. I successfully create child processes and can terminate them on command. I am looking to run code when the process unexpectedly exits, this appears to be what the "exit" event is intended for, but I'm unclear on how to call it, this is the code I am working with, the process runs, but does not detect/log on exit, note that output.append is visual studio code specific version of console.log():

我在节点工作,因为它通过视觉工作室代码扩展发生。我成功创建子进程并可以在命令时终止它们。我希望在进程意外退出时运行代码,这似乎是“退出”事件的目的,但我不清楚如何调用它,这是我正在使用的代码,进程运行,但是不检测/登录退出,请注意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()); 
        });

Here's four things I have tried that do not work in logging on exit:

这里有四件我尝试过的东西不能用于登录退出:

        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 个解决方案

#1


4  

Looking at the node.js source code for the child process module, the .exec() method does this itself:

查看子进程模块的node.js源代码,.exec()方法本身就是这样做的:

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

And, I think .on() is a shortcut for .addListener(), so you could also do:

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

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

#1


4  

Looking at the node.js source code for the child process module, the .exec() method does this itself:

查看子进程模块的node.js源代码,.exec()方法本身就是这样做的:

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

And, I think .on() is a shortcut for .addListener(), so you could also do:

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

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