创建子进程,并在进程被调用后杀死它

Create child process and kill it after the process is invoked

本文关键字:调用 进程 子进程 创建      更新时间:2023-09-26

我使用子进程如下

    var exec = require('child_process').exec;
    var cmd = 'npm install async --save';
    exec(cmd, function(error, stdout, stderr) {
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        if(error || stderr){
            console.error(error);
            console.error(stderr);
            console.log("test");
        }

    });
exec.kill();

我想在进程结束时杀死它,我怎么做呢?我试着像我在帖子中那样导致错误…

  • 如何终止进程
  • 如何验证此进程已终止

exec函数返回一个ChildProcess对象,该对象具有kill方法:

var child = exec(cmd, function(error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if(error || stderr){
        console.error(error);
        console.error(stderr);
        console.log("test");
    }

});
child.kill();

它也有退出事件:

child.on("exit", function (code, signal) {
  if (code === null && signal === "SIGTERM") {
    console.log("child has been terminated");
  }
});