t/bin/unused_listen: simplify this
[rainbows.git] / t / bin / unused_listen
blobcd536f1f72e38199f0aaac5ee56986078a50e2ee
1 #!/usr/bin/env ruby
2 # -*- encoding: binary -*-
3 # this is to remain compatible with the unused_port function in the
4 # Unicorn test/test_helper.rb file
5 require 'socket'
6 require 'tmpdir'
8 default_port = 8080
9 addr = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1'
10 port = sock = lock_path = nil
12 begin
13 sock = TCPServer.new(addr, 0)
14 port = sock.addr[1]
16 # since we'll end up closing the random port we just got, there's a race
17 # condition could allow the random port we just chose to reselect itself
18 # when running tests in parallel with gmake. Create a lock file while
19 # we have the port here to ensure that does not happen.
20 lock_path = "#{Dir::tmpdir}/unicorn_test.#{addr}:#{port}.lock"
21 lock = File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600)
22 rescue Errno::EEXIST
23 sock.close rescue nil
24 retry
25 end
26 sock.close rescue nil
27 puts %Q(listen=#{addr}:#{port} T_RM_LIST="$T_RM_LIST #{lock_path}")