diff --git a/lib/internal/cluster/child.js b/lib/internal/cluster/child.js index 2fc4390e72cbec..3224b3bac4b2c3 100644 --- a/lib/internal/cluster/child.js +++ b/lib/internal/cluster/child.js @@ -111,6 +111,10 @@ cluster._getServer = function(obj, options, cb) { }); obj.once('listening', () => { + // short-lived sockets might have been closed + if (!indexes.has(indexesKey)) { + return; + } cluster.worker.state = 'listening'; const address = obj.address(); message.act = 'listening'; diff --git a/test/parallel/test-dgram-cluster-close-in-listening.js b/test/parallel/test-dgram-cluster-close-in-listening.js new file mode 100644 index 00000000000000..8cce54027164eb --- /dev/null +++ b/test/parallel/test-dgram-cluster-close-in-listening.js @@ -0,0 +1,29 @@ +'use strict'; +// Ensure that closing dgram sockets in 'listening' callbacks of cluster workers +// won't throw errors. + +const common = require('../common'); +const dgram = require('dgram'); +const cluster = require('cluster'); +if (common.isWindows) + common.skip('dgram clustering is currently not supported on windows.'); + +if (cluster.isPrimary) { + for (let i = 0; i < 3; i += 1) { + cluster.fork(); + } +} else { + const socket = dgram.createSocket('udp4'); + + socket.on('error', common.mustNotCall()); + + socket.on('listening', common.mustCall(() => { + socket.close(); + })); + + socket.on('close', common.mustCall(() => { + cluster.worker.disconnect(); + })); + + socket.bind(0); +}