11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ciconst common = require('../common');
31cb0ef41Sopenharmony_ci
41cb0ef41Sopenharmony_ciif (common.isWindows) {
51cb0ef41Sopenharmony_ci  // https://github.com/nodejs/node/issues/48300
61cb0ef41Sopenharmony_ci  common.skip('Does not work with cygwin quirks on Windows');
71cb0ef41Sopenharmony_ci}
81cb0ef41Sopenharmony_ci
91cb0ef41Sopenharmony_ciconst assert = require('assert');
101cb0ef41Sopenharmony_ciconst { spawn } = require('child_process');
111cb0ef41Sopenharmony_ci
121cb0ef41Sopenharmony_ci// Check that, once a child process has ended, it’s safe to read from a pipe
131cb0ef41Sopenharmony_ci// that the child had used as input.
141cb0ef41Sopenharmony_ci// We simulate that using cat | (head -n1; ...)
151cb0ef41Sopenharmony_ci
161cb0ef41Sopenharmony_ciconst p1 = spawn('cat', { stdio: ['pipe', 'pipe', 'inherit'] });
171cb0ef41Sopenharmony_ciconst p2 = spawn('head', ['-n1'], { stdio: [p1.stdout, 'pipe', 'inherit'] });
181cb0ef41Sopenharmony_ci
191cb0ef41Sopenharmony_ci// First, write the line that gets passed through p2, making 'head' exit.
201cb0ef41Sopenharmony_cip1.stdin.write('hello\n');
211cb0ef41Sopenharmony_cip2.stdout.setEncoding('utf8');
221cb0ef41Sopenharmony_cip2.stdout.on('data', common.mustCall((chunk) => {
231cb0ef41Sopenharmony_ci  assert.strictEqual(chunk, 'hello\n');
241cb0ef41Sopenharmony_ci}));
251cb0ef41Sopenharmony_cip2.on('exit', common.mustCall(() => {
261cb0ef41Sopenharmony_ci  // We can now use cat’s output, because 'head' is no longer reading from it.
271cb0ef41Sopenharmony_ci  p1.stdin.end('world\n');
281cb0ef41Sopenharmony_ci  p1.stdout.setEncoding('utf8');
291cb0ef41Sopenharmony_ci  p1.stdout.on('data', common.mustCall((chunk) => {
301cb0ef41Sopenharmony_ci    assert.strictEqual(chunk, 'world\n');
311cb0ef41Sopenharmony_ci  }));
321cb0ef41Sopenharmony_ci  p1.stdout.resume();
331cb0ef41Sopenharmony_ci}));
34