From b44e8cb170a2f8500594153cf8576871f7b46cbd Mon Sep 17 00:00:00 2001 From: Andy Jones Date: Tue, 14 Jul 2015 13:18:33 +0100 Subject: [PATCH] Ensure we remove all paths that we created even if we terminate unexpectedly --- lib/Server/Starter.pm | 15 ++++++++------- lib/Server/Starter/Guard.pm | 9 +++++++-- t/09-guard.t | 28 +++++++++++++++++++++------- 3 files changed, 36 insertions(+), 16 deletions(-) diff --git a/lib/Server/Starter.pm b/lib/Server/Starter.pm index b9b62a8..59f40f0 100644 --- a/lib/Server/Starter.pm +++ b/lib/Server/Starter.pm @@ -150,6 +150,12 @@ sub start_server { } push @sock, $sock; } + my $path_remove_guard = Server::Starter::Guard->new( + sub { + -S $_ and unlink $_ + for @$paths; + }, + ); for my $path (@$paths) { if (-S $path) { warn "removing existing socket file:$path"; @@ -217,6 +223,7 @@ sub start_server { die "fork failed:$!" unless defined $pid; if ($pid != 0) { + $path_remove_guard->dismiss; exit 0; } # in child process @@ -225,6 +232,7 @@ sub start_server { die "fork failed:$!" unless defined $pid; if ($pid != 0) { + $path_remove_guard->dismiss; exit 0; } # do not close STDIN if `--port=n=0`. @@ -235,13 +243,6 @@ sub start_server { } } - my $path_remove_guard = Server::Starter::Guard->new( - sub { - -S $_ and unlink $_ - for @$paths; - }, - ); - # open pid file my $pid_file_guard = sub { return unless $opts->{pid_file}; diff --git a/lib/Server/Starter/Guard.pm b/lib/Server/Starter/Guard.pm index a164000..f25b49c 100644 --- a/lib/Server/Starter/Guard.pm +++ b/lib/Server/Starter/Guard.pm @@ -5,12 +5,17 @@ use warnings; sub new { my ($klass, $handler) = @_; - return bless [ $handler ], $klass; + return bless { + handler => $handler, + active => 1, + }, $klass; } +sub dismiss { shift->{active} = 0 } + sub DESTROY { my $self = shift; - $self->[0]->(); + $self->{active} && $self->{handler}->(); } 1; diff --git a/t/09-guard.t b/t/09-guard.t index f5be031..a51903a 100644 --- a/t/09-guard.t +++ b/t/09-guard.t @@ -4,14 +4,28 @@ use Test::More; use_ok("Server::Starter::Guard"); -my $cnt = 0; +subtest "guard is called when it goes out of scope" => sub { + my $cnt = 0; -my $guard = Server::Starter::Guard->new(sub { - $cnt++; -}); + my $guard = Server::Starter::Guard->new(sub { + $cnt++; + }); -is $cnt, 0; -undef $guard; -is $cnt, 1; + is $cnt, 0; + undef $guard; + is $cnt, 1; +}; + +subtest "guard can be dismissed" => sub { + my $cnt = 0; + + my $guard = Server::Starter::Guard->new(sub { + $cnt++; + }); + + $guard->dismiss; + undef $guard; + is $cnt, 0; +}; done_testing;