| 13 | | |
| 14 | | sub empty_port { |
| 15 | | my $port = shift || 10000; |
| 16 | | $port = 19000 unless $port =~ /^[0-9]+$/ && $port < 19000; |
| 17 | | |
| 18 | | while ($port++ < 20000) { |
| 19 | | my $sock = IO::Socket::INET->new( |
| 20 | | Listen => 5, |
| 21 | | LocalAddr => 'localhost', |
| 22 | | LocalPort => $port, |
| 23 | | Proto => 'tcp' |
| 24 | | ); |
| 25 | | return $port if $sock; |
| 26 | | } |
| 27 | | die "empty port not found"; |
| 28 | | } |
| 29 | | |
| 30 | | sub daemonize (&@) { goto _daemonize } |
| 31 | | sub _daemonize { |
| 32 | | my($client, %args) = @_; |
| 33 | | |
| 34 | | if (my $pid = fork()) { |
| 35 | | # parent. |
| 36 | | sleep 1; # wait startup child process |
| 37 | | |
| 38 | | $client->(); |
| 39 | | |
| 40 | | kill TERM => $pid; |
| 41 | | waitpid($pid, 0); |
| 42 | | } elsif ($pid == 0) { |
| 43 | | # child |
| 44 | | my $poe_kernel_run = delete $args{poe_kernel_run}; |
| 45 | | HTTP::Engine->new(%args)->run; |
| 46 | | POE::Kernel->run() if $poe_kernel_run; |
| 47 | | } else { |
| 48 | | die "cannot fork"; |
| 49 | | } |
| 50 | | } |
| 51 | | |
| 52 | | my @interfaces; # memoize. |
| 53 | | sub interfaces() { |
| 54 | | unless (@interfaces) { |
| 55 | | push @interfaces, 'Standalone'; |
| 56 | | push @interfaces, 'ServerSimple' if eval "use HTTP::Server::Simple; 1;"; |
| 57 | | push @interfaces, 'POE' if eval "use POE; 1;"; |
| 58 | | } |
| 59 | | return @interfaces; |
| 60 | | } |
| 61 | | |
| 62 | | sub daemonize_all (&@) { |
| 63 | | my($client, %args) = @_; |
| 64 | | |
| 65 | | my $poe_kernel_run = delete $args{poe_kernel_run}; |
| 66 | | |
| 67 | | for my $interface (interfaces) { |
| 68 | | $args{interface}->{module} = $interface; |
| 69 | | $args{poe_kernel_run} = ($interface eq 'POE') if $poe_kernel_run; |
| 70 | | _daemonize $client => %args; |
| 71 | | } |
| 72 | | } |