repository moved to https://github.com/moose/MooseX-Daemonize
[gitmo/MooseX-Daemonize.git] / t / 20.core.t
CommitLineData
d8985b7d 1use strict;
2use warnings;
3
45b2dbae 4use Test::More;
e7d94e6a 5use Test::Fatal;
d8985b7d 6use Test::Moose;
380acf65 7use File::Temp qw(tempdir);
8use File::Spec::Functions;
9
10my $dir = tempdir( CLEANUP => 1 );
d8985b7d 11
12BEGIN {
13 use_ok('MooseX::Daemonize::Core');
2ecc2ccb 14 use_ok('MooseX::Daemonize::Pid');
d8985b7d 15}
16
d02fc704 17use constant DEBUG => 0;
18
380acf65 19$ENV{MX_DAEMON_STDOUT} = catfile($dir, 'Out.txt');
20$ENV{MX_DAEMON_STDERR} = catfile($dir, 'Err.txt');
d8985b7d 21
22{
23 package MyFooDaemon;
24 use Moose;
2ecc2ccb 25
d8985b7d 26 with 'MooseX::Daemonize::Core';
2ecc2ccb 27
d8985b7d 28 has 'daemon_pid' => (is => 'rw', isa => 'MooseX::Daemonize::Pid');
2ecc2ccb 29
d8985b7d 30 # capture the PID from the fork
31 around 'daemon_fork' => sub {
32 my $next = shift;
33 my $self = shift;
34 if (my $pid = $self->$next(@_)) {
35 $self->daemon_pid(
36 MooseX::Daemonize::Pid->new(pid => $pid)
37 );
38 }
39 };
2ecc2ccb 40
d8985b7d 41 sub start {
2ecc2ccb 42 my $self = shift;
d8985b7d 43 # tell it to ignore zombies ...
2ecc2ccb 44 $self->ignore_zombies( 1 );
45 $self->no_double_fork( 1 );
46 $self->daemonize;
d8985b7d 47 return unless $self->is_daemon;
48 # change to our local dir
49 # so that we can debug easier
380acf65 50 chdir $dir;
d8985b7d 51 # make it easy to find with ps
52 $0 = 'test-app';
2ecc2ccb 53 $SIG{INT} = sub {
54 print "Got INT! Oh Noes!";
d8985b7d 55 exit;
2ecc2ccb 56 };
d8985b7d 57 while (1) {
2ecc2ccb 58 print "Hello from $$\n";
59 sleep(10);
d8985b7d 60 }
61 exit;
62 }
63}
64
65my $d = MyFooDaemon->new;
66isa_ok($d, 'MyFooDaemon');
67does_ok($d, 'MooseX::Daemonize::Core');
68
e7d94e6a 69is(
70 exception { $d->start },
71 undef,
72 '... successfully daemonized from (' . $$ . ')',
73);
d8985b7d 74
75my $p = $d->daemon_pid;
76isa_ok($p, 'MooseX::Daemonize::Pid');
77
78ok($p->is_running, '... the daemon process is running (' . $p->pid . ')');
79
80my $pid = $p->pid;
d02fc704 81if (DEBUG) {
82 diag `ps $pid`;
83 diag "-------";
84 diag `ps -x | grep test-app`;
85 diag "-------";
86 diag "killing $pid";
87}
d8985b7d 88kill INT => $p->pid;
d02fc704 89diag "killed $pid" if DEBUG;
1474b8d3 90
91# give the process time to be killed on slow/loaded systems
92for (1..10) {
93 last unless kill 0 => $pid;
94 # sleep a little before retrying
95 sleep(2);
96}
97
d02fc704 98if (DEBUG) {
99 diag `ps $pid`;
100 diag "-------";
101 diag `ps -x | grep test-app`;
102}
d8985b7d 103
104ok(!$p->is_running, '... the daemon process is no longer running (' . $p->pid . ')');
105
fe0eeebc 106unlink $ENV{MX_DAEMON_STDOUT};
107unlink $ENV{MX_DAEMON_STDERR};
108
45b2dbae 109done_testing;
d8985b7d 110