Closed
Description
Consider this code:
// parent.js
const childProcess = require('child_process')
console.log('parent:spawning')
const child = childProcess.spawn('node', ['child.js'], {
stdio: ['ignore', 'inherit', 'inherit', 'pipe']
})
const ipc = child.stdio[3]
child.on('close', i => console.log('parent:evt:child:close', i))
child.on('error', i => console.log('parent:evt:child:error', i))
child.on('exit', i => console.log('parent:evt:child:exit', i))
ipc.on('data', i => {
console.log('parent:evt:data', i)
ipc.write('number 2')
})
ipc.on('close', i => console.log('parent:evt:close', i))
ipc.on('error', i => console.log('parent:evt:error', i))
ipc.on('finish', i => console.log('parent:evt:finish', i))
ipc.on('end', i => console.log('parent:evt:end', i))
console.log('parent:writing')
ipc.write('test')
setTimeout(() => process.exit(0), 10000)
// child.js
const fs = require('fs')
console.log('child:start')
setTimeout(() => {
console.log('child:stop')
process.exit(0)
}, 5000)
console.log('child:opening 3')
const writable = fs.createWriteStream(null, {
fd: 3
})
writable.on('error', i => console.log('child:writable:error', i))
writable.on('close', i => console.log('child:writable:close', i))
writable.on('finish', i => console.log('child:writable:finish', i))
writable.on('drain', i => console.log('child:writable:drain', i))
const readable = fs.createReadStream(null, {
fd: 3
})
readable.on('error', i => console.log('child:readable:error', i))
readable.on('data', i => console.log('child:readable:data', i))
readable.on('end', i => console.log('child:readable:end', i))
readable.on('close', i => console.log('child:readable:close', i))
readable.on('readable', i => console.log('child:readable:readable', i))
console.log('child:writing')
writable.write('recv')
The output is more-or-less consistently:
parent:spawning
parent:writing
child:start
child:opening 3
child:writing
parent:evt:data <Buffer 72 65 63 76>
child:readable:data <Buffer 74 65 73 74>
child:readable:data <Buffer 6e 75 6d 62 65 72 20 32>
My question is: If the communication is over one fd
, which I am assuming is an anonymous pipe, how can the parent and child know to not "receive" the data they have just now written? How does that whole process work?
I've been researching file descriptors, pipes and sockets, to mostly not much avail, so I'm hoping someone here can explain it to me.
Metadata
Metadata
Assignees
Labels
No labels