11cb0ef41Sopenharmony_ci'use strict'; 21cb0ef41Sopenharmony_ciconst common = require('../common'); 31cb0ef41Sopenharmony_ciconst assert = require('assert'); 41cb0ef41Sopenharmony_ciconst cp = require('child_process'); 51cb0ef41Sopenharmony_ciconst net = require('net'); 61cb0ef41Sopenharmony_ci 71cb0ef41Sopenharmony_ciif (process.argv[2] !== 'child') { 81cb0ef41Sopenharmony_ci // The parent process forks a child process, starts a TCP server, and connects 91cb0ef41Sopenharmony_ci // to the server. The accepted connection is passed to the child process, 101cb0ef41Sopenharmony_ci // where the socket is written. Then, the child signals the parent process to 111cb0ef41Sopenharmony_ci // write to the same socket. 121cb0ef41Sopenharmony_ci let result = ''; 131cb0ef41Sopenharmony_ci 141cb0ef41Sopenharmony_ci process.on('exit', () => { 151cb0ef41Sopenharmony_ci assert.strictEqual(result, 'childparent'); 161cb0ef41Sopenharmony_ci }); 171cb0ef41Sopenharmony_ci 181cb0ef41Sopenharmony_ci const child = cp.fork(__filename, ['child']); 191cb0ef41Sopenharmony_ci 201cb0ef41Sopenharmony_ci // Verify that the child exits successfully 211cb0ef41Sopenharmony_ci child.on('exit', common.mustCall((exitCode, signalCode) => { 221cb0ef41Sopenharmony_ci assert.strictEqual(exitCode, 0); 231cb0ef41Sopenharmony_ci assert.strictEqual(signalCode, null); 241cb0ef41Sopenharmony_ci })); 251cb0ef41Sopenharmony_ci 261cb0ef41Sopenharmony_ci const server = net.createServer((socket) => { 271cb0ef41Sopenharmony_ci child.on('message', common.mustCall((msg) => { 281cb0ef41Sopenharmony_ci assert.strictEqual(msg, 'child_done'); 291cb0ef41Sopenharmony_ci socket.end('parent', () => { 301cb0ef41Sopenharmony_ci server.close(); 311cb0ef41Sopenharmony_ci child.disconnect(); 321cb0ef41Sopenharmony_ci }); 331cb0ef41Sopenharmony_ci })); 341cb0ef41Sopenharmony_ci 351cb0ef41Sopenharmony_ci child.send('socket', socket, { keepOpen: true }, common.mustSucceed()); 361cb0ef41Sopenharmony_ci }); 371cb0ef41Sopenharmony_ci 381cb0ef41Sopenharmony_ci server.listen(0, () => { 391cb0ef41Sopenharmony_ci const socket = net.connect(server.address().port, common.localhostIPv4); 401cb0ef41Sopenharmony_ci socket.setEncoding('utf8'); 411cb0ef41Sopenharmony_ci socket.on('data', (data) => result += data); 421cb0ef41Sopenharmony_ci }); 431cb0ef41Sopenharmony_ci} else { 441cb0ef41Sopenharmony_ci // The child process receives the socket from the parent, writes data to 451cb0ef41Sopenharmony_ci // the socket, then signals the parent process to write 461cb0ef41Sopenharmony_ci process.on('message', common.mustCall((msg, socket) => { 471cb0ef41Sopenharmony_ci assert.strictEqual(msg, 'socket'); 481cb0ef41Sopenharmony_ci socket.write('child', () => process.send('child_done')); 491cb0ef41Sopenharmony_ci })); 501cb0ef41Sopenharmony_ci} 51