Last active
August 29, 2015 14:10
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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