How to make child process die after parent exits?

后端 未结 24 1774
天涯浪人
天涯浪人 2020-11-22 05:31

Suppose I have a process which spawns exactly one child process. Now when the parent process exits for whatever reason (normally or abnormally, by kill, ^C, assert failure o

24条回答
  •  被撕碎了的回忆
    2020-11-22 06:20

    I found 2 solutions, both not perfect.

    1.Kill all children by kill(-pid) when received SIGTERM signal.
    Obviously, this solution can not handle "kill -9", but it do work for most case and very simple because it need not to remember all child processes.

    
        var childProc = require('child_process').spawn('tail', ['-f', '/dev/null'], {stdio:'ignore'});
    
        var counter=0;
        setInterval(function(){
          console.log('c  '+(++counter));
        },1000);
    
        if (process.platform.slice(0,3) != 'win') {
          function killMeAndChildren() {
            /*
            * On Linux/Unix(Include Mac OS X), kill (-pid) will kill process group, usually
            * the process itself and children.
            * On Windows, an JOB object has been applied to current process and children,
            * so all children will be terminated if current process dies by anyway.
            */
            console.log('kill process group');
            process.kill(-process.pid, 'SIGKILL');
          }
    
          /*
          * When you use "kill pid_of_this_process", this callback will be called
          */
          process.on('SIGTERM', function(err){
            console.log('SIGTERM');
            killMeAndChildren();
          });
        }
    
    

    By same way, you can install 'exit' handler like above way if you call process.exit somewhere. Note: Ctrl+C and sudden crash have automatically been processed by OS to kill process group, so no more here.

    2.Use chjj/pty.js to spawn your process with controlling terminal attached.
    When you kill current process by anyway even kill -9, all child processes will be automatically killed too (by OS?). I guess that because current process hold another side of the terminal, so if current process dies, the child process will get SIGPIPE so dies.

    
        var pty = require('pty.js');
    
        //var term =
        pty.spawn('any_child_process', [/*any arguments*/], {
          name: 'xterm-color',
          cols: 80,
          rows: 30,
          cwd: process.cwd(),
          env: process.env
        });
        /*optionally you can install data handler
        term.on('data', function(data) {
          process.stdout.write(data);
        });
        term.write(.....);
        */
    
    

提交回复
热议问题