Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mislav
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mislav/012e41635d9a5a64a3ee to your computer and use it in GitHub Desktop.
Save mislav/012e41635d9a5a64a3ee to your computer and use it in GitHub Desktop.
Check if TCPServer's port-finding ability is safe with parallelism via fork
# ruby port-finder.rb | cut -f1 -d: | sort -n | uniq -c
#
# Verdict: it seems to be safe on Mac OS X, but it's *not safe* on Linux,
# where causal testing confirms that two subprocesses could pick the same port.
require 'socket'
module PortFinder
def self.call
server = TCPServer.new('127.0.0.1', 0)
server.addr[1]
ensure
server.close if server
end
end
pids = 7.times.map do |num|
fork do
srand
20.times do
sleep((rand/3) + 0.01)
puts "%d: found by process %d" % [
PortFinder.call,
num
]
end
end
end
pids.each do |pid|
Process.wait pid
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment