| 1 |
Author: Niko Tyni <[email protected]> |
| 2 |
Subject: Pipe version: parent waits for the child to say "OK" via a pipe |
| 3 |
Forwarded: http://rt.cpan.org/Public/Bug/Display.html?id=28122 |
| 4 |
Bug: https://rt.cpan.org/Public/Bug/Display.html?id=28122 |
| 5 |
Bug-Debian: #439724, #477227 |
| 6 |
Last-Update: 2015-10-18 |
| 7 |
Reviewed-by: Nicholas Bamber <[email protected]> |
| 8 |
|
| 9 |
--- a/lib/HTTP/Server/Simple.pm |
| 10 |
+++ b/lib/HTTP/Server/Simple.pm |
| 11 |
@@ -5,6 +5,7 @@ |
| 12 |
use FileHandle; |
| 13 |
use Socket; |
| 14 |
use Carp; |
| 15 |
+use IO::Select; |
| 16 |
|
| 17 |
use vars qw($VERSION $bad_request_doc); |
| 18 |
$VERSION = '0.52'; |
| 19 |
@@ -240,9 +241,30 @@ |
| 20 |
|
| 21 |
sub background { |
| 22 |
my $self = shift; |
| 23 |
+ |
| 24 |
+ # set up a pipe so the child can tell the parent when it's ready |
| 25 |
+ # to accept requests |
| 26 |
+ my ($readfh, $writefh) = FileHandle::pipe; |
| 27 |
+ |
| 28 |
my $child = fork; |
| 29 |
croak "Can't fork: $!" unless defined($child); |
| 30 |
- return $child if $child; |
| 31 |
+ |
| 32 |
+ if ($child) { # parent |
| 33 |
+ my $s = IO::Select->new; |
| 34 |
+ $s->add($readfh); |
| 35 |
+ my $now = time; my $left = 0; |
| 36 |
+ my @ready; |
| 37 |
+ while(not @ready and $left < 5) { |
| 38 |
+ @ready = $s->can_read($left); |
| 39 |
+ $left = time - $now; |
| 40 |
+ } |
| 41 |
+ die("child unresponsive for 5 seconds") if(not @ready); |
| 42 |
+ my $response = <$readfh>; |
| 43 |
+ chomp $response; |
| 44 |
+ die("child is confused: answer '$response' != 'OK'") |
| 45 |
+ if $response ne "OK"; |
| 46 |
+ return $child; |
| 47 |
+ } |
| 48 |
|
| 49 |
srand(); # after a fork, we need to reset the random seed |
| 50 |
# or we'll get the same numbers in both branches |
| 51 |
@@ -251,6 +273,8 @@ |
| 52 |
POSIX::setsid() |
| 53 |
or croak "Can't start a new session: $!"; |
| 54 |
} |
| 55 |
+ |
| 56 |
+ $self->{_parent_handle} = $writefh; |
| 57 |
$self->run(@_); # should never return |
| 58 |
exit; # just to be sure |
| 59 |
} |
| 60 |
@@ -300,6 +324,7 @@ |
| 61 |
$self->after_setup_listener(); |
| 62 |
*{"$pkg\::run"} = $self->_default_run; |
| 63 |
} |
| 64 |
+ $self->_maybe_tell_parent(); |
| 65 |
|
| 66 |
local $SIG{HUP} = sub { $SERVER_SHOULD_RUN = 0; }; |
| 67 |
|
| 68 |
@@ -451,6 +476,16 @@ |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
+sub _maybe_tell_parent { |
| 73 |
+ # inform the parent process that we're ready, if applicable |
| 74 |
+ my $self = shift; |
| 75 |
+ my $handle = $self->{_parent_handle}; |
| 76 |
+ return if !$handle; |
| 77 |
+ print $handle "OK\n"; |
| 78 |
+ close $handle; |
| 79 |
+ delete $self->{_parent_handle}; |
| 80 |
+} |
| 81 |
+ |
| 82 |
=head2 stdio_handle [FILEHANDLE] |
| 83 |
|
| 84 |
When called with an argument, sets the socket to the server to that arg. |