From b919ac82118cee2b650b70f99fae185d492d5fe6 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Fri, 2 Jan 2015 23:14:25 -0500 Subject: [PATCH] net: make Server.prototype.unref() persistent Currently, the unref() method does not remember any state if called before the server's handle has been created. This commit adds state to track calls to ref() and unref(). --- lib/net.js | 9 +++++++++ .../test-net-server-unref-persistent.js | 20 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 test/parallel/test-net-server-unref-persistent.js diff --git a/lib/net.js b/lib/net.js index a6c95c6857b9b2..5bf2f292fb76eb 100644 --- a/lib/net.js +++ b/lib/net.js @@ -1038,6 +1038,7 @@ function Server(options, connectionListener) { this._handle = null; this._usingSlaves = false; this._slaves = []; + this._unref = false; this.allowHalfOpen = options.allowHalfOpen || false; this.pauseOnConnect = !!options.pauseOnConnect; @@ -1171,6 +1172,10 @@ Server.prototype._listen2 = function(address, port, addressType, backlog, fd) { // generate connection key, this should be unique to the connection this._connectionKey = addressType + ':' + address + ':' + port; + // unref the handle if the server was unref'ed prior to listening + if (this._unref) + this.unref(); + process.nextTick(function() { // ensure handle hasn't closed if (self._handle) @@ -1440,11 +1445,15 @@ Server.prototype._setupSlave = function(socketList) { }; Server.prototype.ref = function() { + this._unref = false; + if (this._handle) this._handle.ref(); }; Server.prototype.unref = function() { + this._unref = true; + if (this._handle) this._handle.unref(); }; diff --git a/test/parallel/test-net-server-unref-persistent.js b/test/parallel/test-net-server-unref-persistent.js new file mode 100644 index 00000000000000..3a5092b92e0b8f --- /dev/null +++ b/test/parallel/test-net-server-unref-persistent.js @@ -0,0 +1,20 @@ +var common = require('../common'); +var assert = require('assert'); +var net = require('net'); +var closed = false; +var server = net.createServer(); + +// unref before listening +server.unref(); +server.listen(); + +// If the timeout fires, that means the server held the event loop open +// and the unref() was not persistent. Close the server and fail the test. +setTimeout(function() { + closed = true; + server.close(); +}, 1000).unref(); + +process.on('exit', function() { + assert.strictEqual(closed, false, 'server should not hold loop open'); +});