withpidfile should write its pidfile :)
[gitmo/MooseX-Daemonize.git] / lib / MooseX / Daemonize / Core.pm
CommitLineData
18cc5c89 1package MooseX::Daemonize::Core;
18cc5c89 2use Moose::Role;
3
4our $VERSION = 0.01;
5
ea9485d8 6use POSIX ();
18cc5c89 7
8has is_daemon => (
9 isa => 'Bool',
10 is => 'rw',
11 default => sub { 0 },
12);
13
d8985b7d 14sub daemon_fork {
15 my ($self, %options) = @_;
16
17 $SIG{CHLD} = 'IGNORE'
18 if $options{ignore_zombies};
19
129f5643 20 if (my $pid = fork) {
21 return $pid;
22 }
23 else {
289fcbc7 24 $self->is_daemon(1);
129f5643 25 return;
26 }
27}
d8985b7d 28
29sub daemon_detach {
30 my ($self, %options) = @_;
31
32 return unless $self->is_daemon; # return if parent ...
33
34 # now we are in the daemon ...
35
129f5643 36 (POSIX::setsid) # set session id
d8985b7d 37 || confess "Cannot detach from controlling process";
38
39 unless ($options{no_double_fork}) {
40 $SIG{'HUP'} = 'IGNORE';
41 fork && exit;
42 }
43
ea9485d8 44 chdir '/'; # change to root directory
d8985b7d 45 umask 0; # clear the file creation mask
46
ea9485d8 47 # get the max numnber of possible file descriptors
48 my $openmax = POSIX::sysconf( &POSIX::_SC_OPEN_MAX );
49 $openmax = 64 if !defined($openmax) || $openmax < 0;
d8985b7d 50
51 # close them all
ea9485d8 52 POSIX::close($_) foreach (0 .. $openmax);
53
d8985b7d 54 open(STDIN, "+>/dev/null");
55
129f5643 56 if (my $stdout_file = $ENV{MX_DAEMON_STDOUT}) {
d8985b7d 57 open STDOUT, ">", $stdout_file
129f5643 58 or confess "Could not redirect STDOUT to $stdout_file : $!";
59 }
60 else {
61 open(STDOUT, "+>&STDIN");
62 }
63
d8985b7d 64 if (my $stderr_file = $ENV{MX_DAEMON_STDERR}) {
129f5643 65 open STDERR, ">", "ERR.txt"
d8985b7d 66 or confess "Could not redirect STDERR to $stderr_file : $!";
129f5643 67 }
d8985b7d 68 else {
69 open(STDERR, "+>&STDIN");
8ac4733f 70 }
ea9485d8 71}
18cc5c89 72
73sub daemonize {
d8985b7d 74 my ($self, %options) = @_;
75 $self->daemon_fork(%options);
76 $self->daemon_detach(%options);
18cc5c89 77}
78
791;
d8985b7d 80
18cc5c89 81__END__
82
d8985b7d 83=pod
18cc5c89 84
d8985b7d 85=head1 NAME
18cc5c89 86
d8985b7d 87MooseX::Daemonize::Core - A Role with the core daemonization features
18cc5c89 88
89=head1 SYNOPSIS
d8985b7d 90
91 package My::Daemon;
92 use Moose;
93
94 with 'MooseX::Daemonize::Core';
95
96 sub start {
97 my $self = shift;
98 # daemonize me ...
99 $self->daemonize;
100 # return from the parent,...
101 return unless $self->is_daemon;
102 # but continue on in the child (daemon)
103 }
104
18cc5c89 105=head1 DESCRIPTION
106
d8985b7d 107This is the basic daemonization Role, it provides a few methods (see
108below) and the minimum features needed to properly daemonize your code.
109
110=head2 Important Notes
129f5643 111
d8985b7d 112None of the methods in this role will exit the parent process for you,
113it only forks and detaches your child (daemon) process. It is your
114responsibility to exit the parent process in some way.
115
116There is no PID or PID file management in this role, that is your
117responsibility (see some of the other roles in this distro for that).
129f5643 118
18cc5c89 119=head1 ATTRIBUTES
120
121=over
122
129f5643 123=item I<is_daemon (is => rw, isa => Bool)>
18cc5c89 124
d8985b7d 125This attribute is used to signal if we are within the
126daemon process or not.
18cc5c89 127
128=back
129
d8985b7d 130=head1 METHODS
18cc5c89 131
132=over
133
d8985b7d 134=item B<daemon_fork (%options)>
129f5643 135
d8985b7d 136This forks off the child process to be daemonized. Just as with
137the built in fork, it returns the child pid to the parent process,
1380 to the child process. It will also set the is_daemon flag
129f5643 139appropriately.
140
d8985b7d 141The C<%options> available for this function are:
142
143=over 4
144
145=item I<ignore_zombies>
146
147Setting this key to a true value will result in setting the C<$SIG{CHLD}>
148handler to C<IGNORE>. This tells perl to clean up zombie processes. By
149default, and for the most part you don't I<need> it, only when you turn off
150the double fork behavior (with the I<no_double_fork> option) in C<daemon_detach>
151do you sometimes want this behavior.
152
153=back
154
155=item B<daemon_detach (%options)>
129f5643 156
d8985b7d 157This detaches the new child process from the terminal by doing
158the following things.
129f5643 159
160=over 4
161
d8985b7d 162=item Becomes a session leader
18cc5c89 163
d8985b7d 164This detaches the program from the controlling terminal, it is
129f5643 165accomplished by calling POSIX::setsid.
18cc5c89 166
d8985b7d 167=item Performing the double-fork
168
169See below for information on how to change this part of the process.
170
129f5643 171=item Changes the current working directory to "/"
18cc5c89 172
d8985b7d 173This is standard daemon behavior, if you want a different working
174directory then simply change it later in your daemons code.
18cc5c89 175
129f5643 176=item Clears the file creation mask.
18cc5c89 177
129f5643 178=item Closes all open file descriptors.
18cc5c89 179
129f5643 180=item Reopen STDERR, STDOUT & STDIN to /dev/null
18cc5c89 181
d8985b7d 182This behavior can be controlled slightly though the MX_DAEMON_STDERR
129f5643 183and MX_DAEMON_STDOUT environment variables. It will look for a filename
184in either of these variables and redirect STDOUT and/or STDERR to those
185files. This is useful for debugging and/or testing purposes.
18cc5c89 186
129f5643 187-back
18cc5c89 188
d8985b7d 189The C<%options> available for this function are:
190
191=over 4
192
193=item I<no_double_fork>
194
195Setting this option to true will cause this method to not perform the
196typical double-fork, which is extra added protection from your process
197accidentally aquiring a controlling terminal. More information can be
198found above, and by Googling "double fork daemonize".
129f5643 199
d8985b7d 200If you the double-fork behavior off, you might want to enable the
201I<ignore_zombies> behavior in the C<daemon_fork> method.
202
203=back
204
205B<NOTE>
206
207If called from within the parent process (the is_daemon flag is set to
208false), this method will simply return and do nothing.
209
210=item B<daemonize (%options)>
211
212This will simply call C<daemon_fork> followed by C<daemon_detach>, it will
213pass any C<%options> onto both methods.
18cc5c89 214
215=item meta()
216
217The C<meta()> method from L<Class::MOP::Class>
218
219=back
220
d8985b7d 221=head1 STUFF YOU SHOULD READ
222
223=over 4
224
225=item Note about double fork
226
227Taken from L<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012>
228in a comment entitled I<The second fork _is_ necessary by Jonathan Bartlett>,
229it is not the definitive statement on the issue, but it's clear and well
230written enough so I decided to reproduce it here.
231
232 The first fork accomplishes two things - allow the shell to return,
233 and allow you to do a setsid().
234
235 The setsid() removes yourself from your controlling terminal. You
236 see, before, you were still listed as a job of your previous process,
237 and therefore the user might accidentally send you a signal. setsid()
238 gives you a new session, and removes the existing controlling terminal.
239
240 The problem is, you are now a session leader. As a session leader, if
241 you open a file descriptor that is a terminal, it will become your
242 controlling terminal (oops!). Therefore, the second fork makes you NOT
243 be a session leader. Only session leaders can acquire a controlling
244 terminal, so you can open up any file you wish without worrying that
245 it will make you a controlling terminal.
246
247 So - first fork - allow shell to return, and permit you to call setsid()
248
249 Second fork - prevent you from accidentally reacquiring a controlling
250 terminal.
251
252That said, you don't always want this to be the behavior, so you are
253free to specify otherwise using the C<%options>.
254
255=item Note about zombies
256
257Doing the double fork (see above) tends to get rid of your zombies since
258by the time you have double forked your daemon process is then owned by
259the init process. However, sometimes the double-fork is more than you
260really need, and you want to keep your daemon processes a little closer
261to you. In this case you have to watch out for zombies, you can avoid then
262by just setting the C<ignore_zombies> option (see above).
263
264=back
265
266=head1 ENVIRONMENT VARIABLES
267
268These variables are best just used for debugging and/or testing, but
269not used for actual logging. For that, you should reopen STDOUT/ERR on
270your own.
271
272=over 4
273
274=item B<MX_DAEMON_STDOUT>
275
276A filename to redirect the daemon STDOUT to.
277
278=item B<MX_DAEMON_STDERR>
279
280A filename to redirect the daemon STDERR to.
281
282=back
283
18cc5c89 284=head1 DEPENDENCIES
285
129f5643 286L<Moose::Role>, L<POSIX>
18cc5c89 287
288=head1 INCOMPATIBILITIES
289
18cc5c89 290None reported.
291
18cc5c89 292=head1 BUGS AND LIMITATIONS
293
18cc5c89 294No bugs have been reported.
295
296Please report any bugs or feature requests to
297C<bug-acme-dahut-call@rt.cpan.org>, or through the web interface at
298L<http://rt.cpan.org>.
299
300=head1 SEE ALSO
301
129f5643 302L<Proc::Daemon>
303
d8985b7d 304This code is based B<HEAVILY> on L<Proc::Daemon>, we originally
129f5643 305depended on it, but we needed some more flexibility, so instead
d8985b7d 306we just stole the code.
18cc5c89 307
308=head1 AUTHOR
309
129f5643 310Stevan Little C<< <stevan.little@iinteractive.com> >>
18cc5c89 311
18cc5c89 312=head1 LICENCE AND COPYRIGHT
313
d8985b7d 314Copyright (c) 2007, Chris Prather C<< <perigrin@cpan.org> >>. All rights
18cc5c89 315reserved.
316
129f5643 317Portions heavily borrowed from L<Proc::Daemon> which is copyright Earl Hood.
318
18cc5c89 319This module is free software; you can redistribute it and/or
320modify it under the same terms as Perl itself. See L<perlartistic>.
321
18cc5c89 322=head1 DISCLAIMER OF WARRANTY
323
324BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
325FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
326OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
327PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
328EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
329WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
330ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
331YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
332NECESSARY SERVICING, REPAIR, OR CORRECTION.
333
334IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
335WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
336REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
337LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
338OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
339THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
340RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
341FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
342SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
343SUCH DAMAGES.
d8985b7d 344
345=cut