Search code examples
javascriptnode.jsprocessterminalcommand-line-interface

Node spawn child and unref issue


I'm having to call a command in Node and then essentially hand over to that command's stdio, so when spawning a child process and setting the stdio option to inherit I get exactly the behaviour that I'm after.

That said the parent process remains running until the child process is exited, and whilst it probably won't matter all that much, I'd really prefer to exit the parent process as it's no longer needed.

I've figured out that I can do this by calling child.unref() immediately after spawning the child process, however I'm getting some very strange behaviour when doing this.

E.g:

var child = child_process.spawn('irb', [], {
    detached: true,
    stdio: 'inherit'
  });

child.unref();

The irb repl is running and the parent process has exited, but when typing quit in the irb repl I get this:

qNameError: undefined local variable or method `uit' for main:Object
    from (irb):1
    from /Users/RayViljoen/.rvm/rubies/ruby-1.9.3-p385/bin/irb:16:in `<main>'

This is just one of the examples and substituting irb for node or coffee has similar effects. In fact the issue seems to be similar with most interactive consoles being spawned as a child process and then being removed from the parent process.

Has anyone experienced this or know how to do this correctly?


Solution

  • I'm pretty sure that the "inherit" option is turning your node process into a pipe, so that io is routed to the child process... if you cut your current process, that pipe gets cut... Node is very efficient in terms of piped traffic, and if your script isn't too complex, you can minimize the amount of non GC'd objects before running the child process. I wouldn't worry too much about letting it stick around.