Node: Spawn-ed detached unref-ed child process in Windows still prevents parent from exit

Created on 9 Mar 2016  路  9Comments  路  Source: nodejs/node

  • Version: _v5.7.1_
  • Platform: _Windows 7 64-bit_
  • Subsystem: _Child Process_

If I understand the doc right, this script must not wait for child process exit before own exit:

const cp = require('child_process');
const prc = cp.spawn('notepad', [], {detached: true});
prc.unref();

However it does wait.

child_process invalid windows

All 9 comments

Can you try setting the child process stdio to something that doesn't depend on the parent process.

Yes, you need to add something like stdio: 'ignore' to your spawn() options for the parent process to exit as expected.

Thank you, the stdio: 'ignore' will do it. May be this should be added to the doc as well, in the last paragraph of the options.detached part (in addition to the child process behavior info).

@vsemozhetbyt This information is already in the documentation for options.detached:

When using the detached option to start a long-running process, the process will not stay running in the background after the parent exits unless it is provided with a stdio configuration that is not connected to the parent. If the parent's stdio is inherited, the child will remain attached to the controlling terminal.

Well, it says child process will not stay after the parent exits. It does not say parent process will not exit while the child stays.

The last sentence is the key part. The parent cannot exit if the child is still attached to parent's stdio streams because normally once the parent process exits, those streams go away.

If you say so)

How to capture events from child process if I detach and unref it?
I need to get data from child process. If I set ignore I can't get data.

// cp doens't have stdout when detach and unref
cp.stdout.on('data', data => {
    log(data)
})

// This doesn't work.
cp.on('data', data => {
    log(data)
})

I start an HTTP server in a child process. Since it works forever main process waits forever and can't finish.
How to deal with it in Node.js?

@wzup: make up your mind. Either you want the parent to read data from child as a child, or not.. If the child is fully detached, then how'd you want the parent to directly get anything from it? Either don't detach and let the parent just read it like from normal child, or detach and read it like a normal independent processes do: get any normal IPC channel.. sockets, files, whatever. Simplest way probably would be to make the child to write its log to a temp file, and read that instead, etc.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

akdor1154 picture akdor1154  路  3Comments

sandeepks1 picture sandeepks1  路  3Comments

addaleax picture addaleax  路  3Comments

vsemozhetbyt picture vsemozhetbyt  路  3Comments

filipesilvaa picture filipesilvaa  路  3Comments