|  | 
|  | 1 | +'use strict'; | 
|  | 2 | +const common = require('../common'); | 
|  | 3 | +const assert = require('assert'); | 
|  | 4 | +const cp = require('child_process'); | 
|  | 5 | +const net = require('net'); | 
|  | 6 | + | 
|  | 7 | +if (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.mustCall((err) => { | 
|  | 36 | +      assert.ifError(err); | 
|  | 37 | +    })); | 
|  | 38 | +  }); | 
|  | 39 | + | 
|  | 40 | +  server.listen(common.PORT, () => { | 
|  | 41 | +    const socket = net.connect(common.PORT, common.localhostIPv4); | 
|  | 42 | +    socket.setEncoding('utf8'); | 
|  | 43 | +    socket.on('data', (data) => result += data); | 
|  | 44 | +  }); | 
|  | 45 | +} else { | 
|  | 46 | +  // The child process receives the socket from the parent, writes data to | 
|  | 47 | +  // the socket, then signals the parent process to write | 
|  | 48 | +  process.on('message', common.mustCall((msg, socket) => { | 
|  | 49 | +    assert.strictEqual(msg, 'socket'); | 
|  | 50 | +    socket.write('child', () => process.send('child_done')); | 
|  | 51 | +  })); | 
|  | 52 | +} | 
0 commit comments