sending a file handle to a child process

443 views
Skip to first unread message

Tim Kuijsten

unread,
Mar 5, 2015, 8:31:38 PM3/5/15
to nod...@googlegroups.com
I assumed it was possible to send file descriptors or even complete file
streams to a child process using child.send(msg, fd) just like network
sockets.

Unfortunately I just discovered this doesn't work. Both with fs.open and
fs.createWriteStream I get the error "This handle type can't be sent".
The goal is to send a handle to a log file to an unprivileged child.


parent.js:
var fs = require('fs');
var fork = require('child_process').fork;

var child = fork('child.js', { silent: true });

//var file = fs.createWriteStream('/tmp/some.log', { flags: 'a' });
var file = fs.openSync('/tmp/some.log', 'a');

child.on('message', function(msg) {
console.log('parent: msg from child: "%s"', msg);
child.send('from parent', file);
});


child.js:
process.send('from child');

child.on('message', function(msg, fd) {
console.log('child: msg from parent: "%s"', msg, fd);
});


$ node parent.js
parent: msg from child: "from child"
child_process.js:428
throw new TypeError("This handle type can't be sent");
^
TypeError: This handle type can't be sent
at ChildProcess.target._send (child_process.js:428:15)
at ChildProcess.target.send (child_process.js:398:12)
at ChildProcess.<anonymous> (/Users/tim/temp/parent.js:12:9)
at emitTwo (events.js:87:13)
at ChildProcess.emit (events.js:169:7)
at handleMessage (child_process.js:306:10)
at Pipe.channel.onread (child_process.js:334:11)

Tim Kuijsten

unread,
Mar 9, 2015, 10:37:03 AM3/9/15
to nod...@googlegroups.com
For those looking for an answer.

I was confused because it is possible to send an arbitrary amount of
fd's when spawning a process, including stream objects. So I changed to
using this pattern. It actually is much nicer for passing the log files
than doing it after the process is forked. Still I think it would
benefit the API if the same types of objects can be used in sending a
handle as can be passed on spawning.

-Tim


Tim Kuijsten schreef op 06-03-15 om 01:00:
Reply all
Reply to author
Forward
0 new messages