1 package MooseX::Daemonize::Core;
2 use strict; # cause Perl::Critic errors are annoying
3 use MooseX::Getopt; # to load the NoGetopt metaclass
12 # this should never be accessible
13 # from the command line
15 metaclass => 'NoGetopt',
22 my ($self, %options) = @_;
25 if $options{ignore_zombies};
37 my ($self, %options) = @_;
39 return unless $self->is_daemon; # return if parent ...
41 # now we are in the daemon ...
43 (POSIX::setsid) # set session id
44 || confess "Cannot detach from controlling process";
46 unless ($options{no_double_fork}) {
47 $SIG{'HUP'} = 'IGNORE';
51 chdir '/'; # change to root directory
52 umask 0; # clear the file creation mask
54 # get the max numnber of possible file descriptors
55 my $openmax = POSIX::sysconf( &POSIX::_SC_OPEN_MAX );
56 $openmax = 64 if !defined($openmax) || $openmax < 0;
59 POSIX::close($_) foreach (0 .. $openmax);
63 open(STDIN, "+>/dev/null")
64 or confess "Could not redirect STDOUT to /dev/null";
68 if (my $stdout_file = $ENV{MX_DAEMON_STDOUT}) {
69 open STDOUT, ">", $stdout_file
70 or confess "Could not redirect STDOUT to $stdout_file : $!";
73 open(STDOUT, "+>&STDIN")
74 or confess "Could not redirect STDOUT to /dev/null";
79 if (my $stderr_file = $ENV{MX_DAEMON_STDERR}) {
80 open STDERR, ">", "ERR.txt"
81 or confess "Could not redirect STDERR to $stderr_file : $!";
84 open(STDERR, "+>&STDIN")
85 or confess "Could not redirect STDERR to /dev/null"; ;
88 # do a little house cleaning ...
90 # Avoid 'stdin reopened for output'
91 # warning with newer perls
92 open( NULL, '/dev/null' );
100 my ($self, %options) = @_;
101 $self->daemon_fork(%options);
102 $self->daemon_detach(%options);
113 MooseX::Daemonize::Core - A Role with the core daemonization features
120 with 'MooseX::Daemonize::Core';
126 # return from the parent,...
127 return unless $self->is_daemon;
128 # but continue on in the child (daemon)
133 This is the basic daemonization Role, it provides a few methods (see
134 below) and the minimum features needed to properly daemonize your code.
136 =head2 Important Notes
138 None of the methods in this role will exit the parent process for you,
139 it only forks and detaches your child (daemon) process. It is your
140 responsibility to exit the parent process in some way.
142 There is no PID or PID file management in this role, that is your
143 responsibility (see some of the other roles in this distro for that).
149 =item I<is_daemon (is => rw, isa => Bool)>
151 This attribute is used to signal if we are within the
152 daemon process or not.
160 =item B<daemon_fork (%options)>
162 This forks off the child process to be daemonized. Just as with
163 the built in fork, it returns the child pid to the parent process,
164 0 to the child process. It will also set the is_daemon flag
167 The C<%options> available for this function are:
171 =item I<ignore_zombies>
173 Setting this key to a true value will result in setting the C<$SIG{CHLD}>
174 handler to C<IGNORE>. This tells perl to clean up zombie processes. By
175 default, and for the most part you don't I<need> it, only when you turn off
176 the double fork behavior (with the I<no_double_fork> option) in C<daemon_detach>
177 do you sometimes want this behavior.
181 =item B<daemon_detach (%options)>
183 This detaches the new child process from the terminal by doing
184 the following things.
188 =item Becomes a session leader
190 This detaches the program from the controlling terminal, it is
191 accomplished by calling POSIX::setsid.
193 =item Performing the double-fork
195 See below for information on how to change this part of the process.
197 =item Changes the current working directory to "/"
199 This is standard daemon behavior, if you want a different working
200 directory then simply change it later in your daemons code.
202 =item Clears the file creation mask.
204 =item Closes all open file descriptors.
206 =item Reopen STDERR, STDOUT & STDIN to /dev/null
208 This behavior can be controlled slightly though the MX_DAEMON_STDERR
209 and MX_DAEMON_STDOUT environment variables. It will look for a filename
210 in either of these variables and redirect STDOUT and/or STDERR to those
211 files. This is useful for debugging and/or testing purposes.
215 The C<%options> available for this function are:
219 =item I<no_double_fork>
221 Setting this option to true will cause this method to not perform the
222 typical double-fork, which is extra added protection from your process
223 accidentally aquiring a controlling terminal. More information can be
224 found above, and by Googling "double fork daemonize".
226 If you the double-fork behavior off, you might want to enable the
227 I<ignore_zombies> behavior in the C<daemon_fork> method.
233 If called from within the parent process (the is_daemon flag is set to
234 false), this method will simply return and do nothing.
236 =item B<daemonize (%options)>
238 This will simply call C<daemon_fork> followed by C<daemon_detach>, it will
239 pass any C<%options> onto both methods.
243 The C<meta()> method from L<Class::MOP::Class>
247 =head1 STUFF YOU SHOULD READ
251 =item Note about double fork
253 Taken from L<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012>
254 in a comment entitled I<The second fork _is_ necessary by Jonathan Bartlett>,
255 it is not the definitive statement on the issue, but it's clear and well
256 written enough so I decided to reproduce it here.
258 The first fork accomplishes two things - allow the shell to return,
259 and allow you to do a setsid().
261 The setsid() removes yourself from your controlling terminal. You
262 see, before, you were still listed as a job of your previous process,
263 and therefore the user might accidentally send you a signal. setsid()
264 gives you a new session, and removes the existing controlling terminal.
266 The problem is, you are now a session leader. As a session leader, if
267 you open a file descriptor that is a terminal, it will become your
268 controlling terminal (oops!). Therefore, the second fork makes you NOT
269 be a session leader. Only session leaders can acquire a controlling
270 terminal, so you can open up any file you wish without worrying that
271 it will make you a controlling terminal.
273 So - first fork - allow shell to return, and permit you to call setsid()
275 Second fork - prevent you from accidentally reacquiring a controlling
278 That said, you don't always want this to be the behavior, so you are
279 free to specify otherwise using the C<%options>.
281 =item Note about zombies
283 Doing the double fork (see above) tends to get rid of your zombies since
284 by the time you have double forked your daemon process is then owned by
285 the init process. However, sometimes the double-fork is more than you
286 really need, and you want to keep your daemon processes a little closer
287 to you. In this case you have to watch out for zombies, you can avoid then
288 by just setting the C<ignore_zombies> option (see above).
292 =head1 ENVIRONMENT VARIABLES
294 These variables are best just used for debugging and/or testing, but
295 not used for actual logging. For that, you should reopen STDOUT/ERR on
300 =item B<MX_DAEMON_STDOUT>
302 A filename to redirect the daemon STDOUT to.
304 =item B<MX_DAEMON_STDERR>
306 A filename to redirect the daemon STDERR to.
312 L<Moose::Role>, L<POSIX>
314 =head1 INCOMPATIBILITIES
318 =head1 BUGS AND LIMITATIONS
320 No bugs have been reported.
322 Please report any bugs or feature requests to
323 C<bug-acme-dahut-call@rt.cpan.org>, or through the web interface at
324 L<http://rt.cpan.org>.
330 This code is based B<HEAVILY> on L<Proc::Daemon>, we originally
331 depended on it, but we needed some more flexibility, so instead
332 we just stole the code.
336 Stevan Little C<< <stevan.little@iinteractive.com> >>
338 =head1 LICENCE AND COPYRIGHT
340 Copyright (c) 2007, Chris Prather C<< <perigrin@cpan.org> >>. All rights
343 Portions heavily borrowed from L<Proc::Daemon> which is copyright Earl Hood.
345 This module is free software; you can redistribute it and/or
346 modify it under the same terms as Perl itself. See L<perlartistic>.
348 =head1 DISCLAIMER OF WARRANTY
350 BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
351 FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
352 OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
353 PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
354 EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
355 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
356 ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
357 YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
358 NECESSARY SERVICING, REPAIR, OR CORRECTION.
360 IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
361 WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
362 REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE
363 LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL,
364 OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE
365 THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
366 RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
367 FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
368 SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF