1// Copyright Joyent, Inc. and other Node contributors. 2// 3// Permission is hereby granted, free of charge, to any person obtaining a 4// copy of this software and associated documentation files (the 5// "Software"), to deal in the Software without restriction, including 6// without limitation the rights to use, copy, modify, merge, publish, 7// distribute, sublicense, and/or sell copies of the Software, and to permit 8// persons to whom the Software is furnished to do so, subject to the 9// following conditions: 10// 11// The above copyright notice and this permission notice shall be included 12// in all copies or substantial portions of the Software. 13// 14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 20// USE OR OTHER DEALINGS IN THE SOFTWARE. 21 22'use strict'; 23// Check that having a worker bind to a port that's already taken doesn't 24// leave the primary process in a confused state. Releasing the port and 25// trying again should Just Work[TM]. 26 27const common = require('../common'); 28const assert = require('assert'); 29const fork = require('child_process').fork; 30const net = require('net'); 31 32const id = String(process.argv[2]); 33const port = String(process.argv[3]); 34 35if (id === 'undefined') { 36 const server = net.createServer(common.mustNotCall()); 37 server.listen(0, function() { 38 const worker = fork(__filename, ['worker', server.address().port]); 39 worker.on('message', function(msg) { 40 if (msg !== 'stop-listening') return; 41 server.close(function() { 42 worker.send('stopped-listening'); 43 }); 44 }); 45 }); 46} else if (id === 'worker') { 47 let server = net.createServer(common.mustNotCall()); 48 server.listen(port, common.mustNotCall()); 49 server.on('error', common.mustCall(function(e) { 50 assert(e.code, 'EADDRINUSE'); 51 process.send('stop-listening'); 52 process.once('message', function(msg) { 53 if (msg !== 'stopped-listening') return; 54 server = net.createServer(common.mustNotCall()); 55 server.listen(port, common.mustCall(function() { 56 server.close(); 57 })); 58 }); 59 })); 60} else { 61 assert(0); // Bad argument. 62} 63