Search code examples
javascriptnode.jschild-processspawn

Create child process and kill it after the process is invoked


I use child process as follows

    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();

I want that when the process finished kill it,how I can do that? I try like I put in the post which cause errors...

  • how to kill process
  • how to veify that this process killed

Solution

  • The exec function returns a ChildProcess object, which has the kill method:

    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();
    

    It also has the exit event:

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