unicorn 4.6.0pre1 - hijacking support
[unicorn.git] / t / bin / unused_listen
blobb638f54ce2f6e0a09d55b0cbdc74534ff027931c
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 retries = 100
11 base = 5000
12 port = sock = lock_path = nil
14 begin
15 begin
16 port = base + rand(32768 - base)
17 while port == default_port
18 port = base + rand(32768 - base)
19 end
21 sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
22 sock.bind(Socket.pack_sockaddr_in(port, addr))
23 sock.listen(5)
24 rescue Errno::EADDRINUSE, Errno::EACCES
25 sock.close rescue nil
26 retry if (retries -= 1) >= 0
27 end
29 # since we'll end up closing the random port we just got, there's a race
30 # condition could allow the random port we just chose to reselect itself
31 # when running tests in parallel with gmake. Create a lock file while
32 # we have the port here to ensure that does not happen.
33 lock_path = "#{Dir::tmpdir}/unicorn_test.#{addr}:#{port}.lock"
34 lock = File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600)
35 rescue Errno::EEXIST
36 sock.close rescue nil
37 retry
38 end
39 sock.close rescue nil
40 puts %Q(listen=#{addr}:#{port} T_RM_LIST="$T_RM_LIST #{lock_path}")