11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ci
31cb0ef41Sopenharmony_ci// Ref: https://github.com/nodejs/node/issues/32106
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ciconst common = require('../common');
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ciconst assert = require('assert');
81cb0ef41Sopenharmony_ciconst cluster = require('cluster');
91cb0ef41Sopenharmony_ciconst os = require('os');
101cb0ef41Sopenharmony_ci
111cb0ef41Sopenharmony_ciif (cluster.isPrimary) {
121cb0ef41Sopenharmony_ci  const workers = [];
131cb0ef41Sopenharmony_ci  const numCPUs = os.availableParallelism();
141cb0ef41Sopenharmony_ci  let waitOnline = numCPUs;
151cb0ef41Sopenharmony_ci  for (let i = 0; i < numCPUs; i++) {
161cb0ef41Sopenharmony_ci    const worker = cluster.fork();
171cb0ef41Sopenharmony_ci    workers[i] = worker;
181cb0ef41Sopenharmony_ci    worker.once('online', common.mustCall(() => {
191cb0ef41Sopenharmony_ci      if (--waitOnline === 0)
201cb0ef41Sopenharmony_ci        for (const worker of workers)
211cb0ef41Sopenharmony_ci          if (worker.isConnected())
221cb0ef41Sopenharmony_ci            worker.send(i % 2 ? 'disconnect' : 'destroy');
231cb0ef41Sopenharmony_ci    }));
241cb0ef41Sopenharmony_ci
251cb0ef41Sopenharmony_ci    // These errors can occur due to the nature of the test, we might be trying
261cb0ef41Sopenharmony_ci    // to send messages when the worker is disconnecting.
271cb0ef41Sopenharmony_ci    worker.on('error', (err) => {
281cb0ef41Sopenharmony_ci      assert.strictEqual(err.syscall, 'write');
291cb0ef41Sopenharmony_ci      if (common.isOSX) {
301cb0ef41Sopenharmony_ci        assert(['EPIPE', 'ENOTCONN'].includes(err.code), err);
311cb0ef41Sopenharmony_ci      } else {
321cb0ef41Sopenharmony_ci        assert(['EPIPE', 'ECONNRESET'].includes(err.code), err);
331cb0ef41Sopenharmony_ci      }
341cb0ef41Sopenharmony_ci    });
351cb0ef41Sopenharmony_ci
361cb0ef41Sopenharmony_ci    worker.once('disconnect', common.mustCall(() => {
371cb0ef41Sopenharmony_ci      for (const worker of workers)
381cb0ef41Sopenharmony_ci        if (worker.isConnected())
391cb0ef41Sopenharmony_ci          worker.send('disconnect');
401cb0ef41Sopenharmony_ci    }));
411cb0ef41Sopenharmony_ci
421cb0ef41Sopenharmony_ci    worker.once('exit', common.mustCall((code, signal) => {
431cb0ef41Sopenharmony_ci      assert.strictEqual(code, 0);
441cb0ef41Sopenharmony_ci      assert.strictEqual(signal, null);
451cb0ef41Sopenharmony_ci    }));
461cb0ef41Sopenharmony_ci  }
471cb0ef41Sopenharmony_ci} else {
481cb0ef41Sopenharmony_ci  process.on('message', (msg) => {
491cb0ef41Sopenharmony_ci    if (cluster.worker.isConnected())
501cb0ef41Sopenharmony_ci      cluster.worker[msg]();
511cb0ef41Sopenharmony_ci  });
521cb0ef41Sopenharmony_ci}
53