简体   繁体   中英

Port finding race condition

I have a master.js and a slave.js

Whenever the master.js needs more slaves to handle data, it will .fork them.

In slave.js (truncated)

portscanner.findAPortNotInUse(config.wss.start_port, config.wss.end_port)
.then((port) => {
    httpsServer.listen(port);
    process.send('Connected and listening on : ' + port);
})

Start Port is 11001 and End Port is 11100.

Now sometimes slave4 and slave5 both think that 11004 is free, both bind to that port and throw EADDRINUSE.

master.js

function CreateSlave(mode, amount) {
    return new Promise((res) => {

        var c = connected_slaves;
        for (var i = 0; i < amount; i++) {

            var id = uuid.v4().split("-")[0];

            slaves[c] = fork('/opt/nodeapps/ass/slave/server.js',
            [serverKeyForSession, mode]);
            slaves[c].id = id;
            slaves[c].mode = mode;

            AttachHandlerToSlave(c).then((res) => {
                if (res) return;
            });
            c++;
        }
    });
}

function AttachHandlerToSlave(c) {
    return new Promise((res, rej) => {
        slaves[c].on('message', (msg) => {
            console.log('\x1b[33m['+ slaves[c].id +'] | \x1b[0m'+msg);
        });
        res(true);
    });
}

How can I prevent such behavior?

You can make your master process to transmit the port number to the slaves .

When forking you automatically open a channel of communication between the master and the slave . Use it.

Here is a good tutorial about child processes.


I quote :


parent.js

const { fork } = require('child_process');

const forked = fork('child.js');

forked.on('message', (msg) => {
  console.log('Message from child', msg);
});

forked.send({ hello: 'world' });

slave.js

process.on('message', (msg) => {
  console.log('Message from parent:', msg);
});

let counter = 0;

setInterval(() => {
  process.send({ counter: counter++ });
}, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM