From 3b94fc19e8f323cb373331ebf113a2bec6f0015c Mon Sep 17 00:00:00 2001 From: Erick Wendel Date: Fri, 17 Dec 2021 12:04:29 -0300 Subject: [PATCH] lib: child process queue pending messages It fixes the problem for the child process not receiving messages. Fixes: https://github.com/nodejs/node/issues/41134 --- lib/internal/child_process.js | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index 40592146ada6de..f6c98e09fd4fa0 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -59,6 +59,7 @@ const { convertToValidSignal, deprecate } = require('internal/util'); const { isArrayBufferView } = require('internal/util/types'); const spawn_sync = internalBinding('spawn_sync'); const { kStateSymbol } = require('internal/dgram'); +const console = require('console'); const { UV_EACCES, @@ -526,6 +527,7 @@ class Control extends EventEmitter { constructor(channel) { super(); this.#channel = channel; + this.pendingMessages = new Set(); } // The methods keeping track of the counter are being used to track the @@ -699,6 +701,19 @@ function setupChannel(target, channel, serializationMode) { }); }); + target.on('newListener', function () { + if(!target.channel) return; + + const messages = target.channel.pendingMessages; + if (!messages.size) return; + + for (const messageParams of messages) { + process.nextTick(target.emit.bind(target), ...messageParams); + } + + messages.clear(); + }); + target.send = function(message, handle, options, callback) { if (typeof handle === 'function') { callback = handle; @@ -912,7 +927,15 @@ function setupChannel(target, channel, serializationMode) { }; function emit(event, message, handle) { - target.emit(event, message, handle); + const args = [event, message, handle]; + const isInternalMessage = "internalMessage" === event; + const hasListenersInstalled = target.listenerCount('message'); + if (hasListenersInstalled || isInternalMessage) { + target.emit(...args); + return; + } + + target.channel.pendingMessages.add(args); } function handleMessage(message, handle, internal) {