joyent/node — pull request #2832 by AvianFlu (2012-02-26 20:30:10+00:00)
Title: child_process: Expose 'detached' option to allow spawning detached child processes

This functionality now [exists in libuv master](https://github.com/joyent/libuv/compare/f6c8e78d...ea9baef) - `uv_spawn()` is now able to spawn detached (i.e. daemonized) child processes on both unix and Windows.

This patch exposes that option to Node.JS userland as a `detached` option to `child_process.spawn`.

```js

var spawn = require('child_process').spawn;

var child = spawn('server.js', ['-p', '80'], {
detached: true
});

child.on('detached', function (pid) {
console.log('Child is now detached. pid: %d.', pid);
});
```
Despite the fact that the `stdio` streams created in js are closed in `libuv`, the child closing its streams and exiting isn't enough to tell `child_process.js` that the child has exited.

`this._internal.onexit` is called successfully, but the `maybeExit` function is explicitly waiting for `close` events from the number of streams that were opened in js. Despite the fact that the underlying streams have been closed, the `close` events on the `stdio` streams in node don't fire of their own accord.

This keeps the parent process alive indefinitely, as the criteria specified for emitting the `exit` event will never occur.

Since a detached process is semantically somewhat different than a normal child process that exits, a separate `detached` event seemed like a good way to solve this. If the process being spawned is detached, the parent now emits a `detached` event without waiting for the other `close` events.

It might be better to somehow close or destroy the `stdout` and `stderr` streams, but the event loop doesn't seem to care, and node exits just fine.