1'use strict'; 2const common = require('../common'); 3const assert = require('assert'); 4const cp = require('child_process'); 5const net = require('net'); 6 7if (process.argv[2] !== 'child') { 8 // The parent process forks a child process, starts a TCP server, and connects 9 // to the server. The accepted connection is passed to the child process, 10 // where the socket is written. Then, the child signals the parent process to 11 // write to the same socket. 12 let result = ''; 13 14 process.on('exit', () => { 15 assert.strictEqual(result, 'childparent'); 16 }); 17 18 const child = cp.fork(__filename, ['child']); 19 20 // Verify that the child exits successfully 21 child.on('exit', common.mustCall((exitCode, signalCode) => { 22 assert.strictEqual(exitCode, 0); 23 assert.strictEqual(signalCode, null); 24 })); 25 26 const server = net.createServer((socket) => { 27 child.on('message', common.mustCall((msg) => { 28 assert.strictEqual(msg, 'child_done'); 29 socket.end('parent', () => { 30 server.close(); 31 child.disconnect(); 32 }); 33 })); 34 35 child.send('socket', socket, { keepOpen: true }, common.mustSucceed()); 36 }); 37 38 server.listen(0, () => { 39 const socket = net.connect(server.address().port, common.localhostIPv4); 40 socket.setEncoding('utf8'); 41 socket.on('data', (data) => result += data); 42 }); 43} else { 44 // The child process receives the socket from the parent, writes data to 45 // the socket, then signals the parent process to write 46 process.on('message', common.mustCall((msg, socket) => { 47 assert.strictEqual(msg, 'socket'); 48 socket.write('child', () => process.send('child_done')); 49 })); 50} 51