Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stdout/stderr from a child_process to /dev/null or something similar

I am creating some child_processes with Node.js (require('child_process')) and I want to ensure that the stdout/stderr from each child_process does not go to the terminal, because I want only the output from the parent process to get logged. Is there a way to redirect the stdout/stderr streams in the child_processes to /dev/null or some other place that is not the terminal?

https://nodejs.org/api/child_process.html

perhaps it's just:

var n = cp.fork('child.js',[],{
   stdio: ['ignore','ignore','ignore']
});

I just tried that, and that didn't seem to work.

Now I tried this:

var stdout, stderr;

if (os.platform() === 'win32') {
    stdout = fs.openSync('NUL', 'a');
    stderr = fs.openSync('NUL', 'a');
}
else {
    stdout = fs.openSync('/dev/null', 'a');
    stderr = fs.openSync('/dev/null', 'a');
}

and then this option:

stdio: ['ignore',  stdout, stderr],

but that didn't do it, but it seems like using the "detached:true" option might make this work.

like image 349
Alexander Mills Avatar asked Mar 13 '23 09:03

Alexander Mills


1 Answers

Solution:

To throw away the stdout and stderr of a forked childprocess:

  1. setup a pipe i.e. use silent = True when forking.

  2. And redirect the stdout and stderr pipes on the parent process into /dev/null.


Explanation:

The node.js documentation states :

For convenience, options.stdio may be one of the following strings:

'pipe' - equivalent to ['pipe', 'pipe', 'pipe'] (the default)
'ignore' - equivalent to ['ignore', 'ignore', 'ignore']
'inherit' - equivalent to [process.stdin, process.stdout, process.stderr] or [0,1,2]

Apparently childprocess.fork() does NOT support ignore; Only childprocess.spawn() does.

fork does support a silent option that allows one to choose between pipe OR inherit.

When forking a child process:
If silent = True, then stdio = pipe.
If silent = False, then stdio = inherit.

silent
Boolean

If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent.

See the 'pipe' and 'inherit' options for child_process.spawn()'s stdio for more details.

like image 164
TheCodeArtist Avatar answered Mar 15 '23 23:03

TheCodeArtist