IO: fix 1.9 encoding bug :<
[sunshowers.git] / t / bin / unused_listen
blob95f32498084faa2e34373f36cfe5af1d62bac1ed
1 #!/usr/bin/env ruby
2 # this is to remain compatible with the unused_port function in the
3 # Unicorn test/test_helper.rb file
4 require 'socket'
5 require 'tmpdir'
7 default_port = 8080
8 addr = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1'
9 retries = 100
10 base = 5000
11 port = sock = lock_path = nil
13 begin
14 begin
15 port = base + rand(32768 - base)
16 while port == default_port
17 port = base + rand(32768 - base)
18 end
20 sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
21 sock.bind(Socket.pack_sockaddr_in(port, addr))
22 sock.listen(5)
23 rescue Errno::EADDRINUSE, Errno::EACCES
24 sock.close rescue nil
25 retry if (retries -= 1) >= 0
26 end
28 # since we'll end up closing the random port we just got, there's a race
29 # condition could allow the random port we just chose to reselect itself
30 # when running tests in parallel with gmake. Create a lock file while
31 # we have the port here to ensure that does not happen.
32 lock_path = "#{Dir::tmpdir}/unicorn_test.#{addr}:#{port}.lock"
33 lock = File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600)
34 rescue Errno::EEXIST
35 sock.close rescue nil
36 retry
37 end
38 sock.close rescue nil
39 puts %Q(listen=#{addr}:#{port} T_RM_LIST="$T_RM_LIST #{lock_path}")