File: Core.pm

package info (click to toggle)
libmoosex-daemonize-perl 0.22-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 420 kB
  • sloc: perl: 766; makefile: 2
file content (407 lines) | stat: -rw-r--r-- 10,886 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use strict;
use warnings;
package MooseX::Daemonize::Core;
# ABSTRACT: A Role with the core daemonization features

our $VERSION = '0.22';

use MooseX::Getopt; # to load the NoGetopt metaclass
use Moose::Role;
use POSIX ();
use namespace::autoclean;

has is_daemon => (
    # NOTE:
    # this should never be accessible
    # from the command line
    # - SL
    metaclass => 'NoGetopt',
    isa       => 'Bool',
    is        => 'rw',
    default   => sub { 0 },
);

has ignore_zombies => (
    metaclass => 'Getopt',
    isa       => 'Bool',
    is        => 'rw',
    default   => sub { 0 },
);

has no_double_fork => (
    metaclass => 'Getopt',
    isa       => 'Bool',
    is        => 'rw',
    default   => sub { 0 },
);

has dont_close_all_files => (
    metaclass => 'Getopt',
    isa       => 'Bool',
    is        => 'rw',
    default   => sub { 0 },
);

sub _get_options {
    my ($self, %options) = @_;
    # backwards compatibility.. old code might be calling daemon_fork/_detach with options
    foreach my $opt (qw( ignore_zombies no_double_fork dont_close_all_files )) {
        $self->$opt( $options{ $opt } ) if ( defined $options{ $opt } );
    }
}


sub daemon_fork {
    my ($self, %options) = @_;

    $self->_get_options( %options );

    $SIG{CHLD} = 'IGNORE'
        if $self->ignore_zombies;;

    if (my $pid = fork) {
        return $pid;
    }
    else {
        $self->is_daemon(1);
        return;
    }
}

sub daemon_detach {
    my ($self, %options) = @_;

    return unless $self->is_daemon; # return if parent ...

    $self->_get_options( %options );
    # now we are in the daemon ...

    POSIX::setsid == -1  # set session id
        and confess "Cannot detach from controlling process";

    unless ( $self->no_double_fork ) {
        $SIG{'HUP'} = 'IGNORE';
        fork && exit;
    }

    chdir '/';      # change to root directory
    umask 0;        # clear the file creation mask

    unless ( $self->dont_close_all_files ) {
        # get the max number of possible file descriptors
        my $openmax = POSIX::sysconf( &POSIX::_SC_OPEN_MAX );
        $openmax = 64 if !defined($openmax) || $openmax < 0;

        # close them all
        POSIX::close($_) foreach (0 .. $openmax);
    }

    # fixup STDIN ...

    open(STDIN, "+>/dev/null")
        or confess "Could not redirect STDOUT to /dev/null";

    # fixup STDOUT ...

    if (my $stdout_file = $ENV{MX_DAEMON_STDOUT}) {
        open STDOUT, ">", $stdout_file
            or confess "Could not redirect STDOUT to $stdout_file : $!";
    }
    else {
        open(STDOUT, "+>&STDIN")
            or confess "Could not redirect STDOUT to /dev/null";
    }

    # fixup STDERR ...

    if (my $stderr_file = $ENV{MX_DAEMON_STDERR}) {
        open STDERR, ">", $stderr_file
            or confess "Could not redirect STDERR to $stderr_file : $!";
    }
    else {
        open(STDERR, "+>&STDIN")
            or confess "Could not redirect STDERR to /dev/null";        ;
    }

    # do a little house cleaning ...

    # Avoid 'stdin reopened for output'
    # warning with newer perls
    open( NULL, '/dev/null' );
    <NULL> if (0);

    # return success
    return 1;
}

sub daemonize {
    my ($self, %options) = @_;
    $self->daemon_fork(%options);
    $self->daemon_detach(%options);
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

MooseX::Daemonize::Core - A Role with the core daemonization features

=head1 VERSION

version 0.22

=head1 SYNOPSIS

  package My::Daemon;
  use Moose;

  with 'MooseX::Daemonize::Core';

  sub start {
      my $self = shift;
      # daemonize me ...
      $self->daemonize;
      # return from the parent,...
      return unless $self->is_daemon;
      # but continue on in the child (daemon)
  }

=head1 DESCRIPTION

This is the basic daemonization Role, it provides a few methods (see
below) and the minimum features needed to properly daemonize your code.

=head2 Important Notes

None of the methods in this role will exit the parent process for you,
it only forks and detaches your child (daemon) process. It is your
responsibility to exit the parent process in some way.

There is no PID or PID file management in this role, that is your
responsibility (see some of the other roles in this distro for that).

=head1 ATTRIBUTES

=over

=item I<is_daemon (is => rw, isa => Bool)>

This attribute is used to signal if we are within the
daemon process or not.

=item I<no_double_fork (is => rw, isa => Bool)>

Setting this attribute to true will cause this method to not perform the
typical double-fork, which is extra added protection from your process
accidentally acquiring a controlling terminal. More information can be
found above, and by Googling "double fork daemonize".

If you the double-fork behavior off, you might want to enable the
I<ignore_zombies>.

=item I<ignore_zombies (is => rw, isa => Bool)>

Setting this attribute to a true value will result in setting the C<$SIG{CHLD}>
handler to C<IGNORE>. This tells perl to clean up zombie processes. By
default, and for the most part you don't I<need> it, only when you turn off
the double fork behavior (with the I<no_double_fork> attribute)
do you sometimes want this behavior.

=item I<dont_close_all_files (is => rw, isa => Bool)>

Setting this attribute to true will cause it to skip closing all the
filehandles. This is useful if you are opening things like sockets
and such in the pre-fork.

=back

=head1 METHODS

=over

=item B<daemon_fork (?%options)>

This forks off the child process to be daemonized. Just as with
the built in fork, it returns the child pid to the parent process,
0 to the child process. It will also set the is_daemon flag
appropriately.

The C<%options> argument remains for backwards compatibility, but
it is suggested that you use the attributes listed above instead.

=item B<daemon_detach (?%options)>

This detaches the new child process from the terminal by doing
the following things.

The C<%options> argument remains for backwards compatibility, but
it is suggested that you use the attributes listed above instead.

=over 4

=item Becomes a session leader

This detaches the program from the controlling terminal, it is
accomplished by calling C<POSIX::setsid>.

=item Performing the double-fork

See below for information on how to change this part of the process.

=item Changes the current working directory to "/"

This is standard daemon behavior, if you want a different working
directory then simply change it later in your daemons code.

=item Clears the file creation mask.

=item Closes all open file descriptors.

See the I<dont_close_all_files> attribute for information on how to
change this part of the process.

=item Reopen STDERR, STDOUT & STDIN to /dev/null

This behavior can be controlled slightly though the C<MX_DAEMON_STDERR>
and C<MX_DAEMON_STDOUT> environment variables. It will look for a filename
in either of these variables and redirect C<STDOUT> and/or C<STDERR> to those
files. This is useful for debugging and/or testing purposes.

B<NOTE>

If called from within the parent process (the C<is_daemon> flag is set to
false), this method will simply return and do nothing.

=item B<daemonize (?%options)>

This will simply call C<daemon_fork> followed by C<daemon_detach>.

The C<%options> argument remains for backwards compatibility, but
it is suggested that you use the attributes listed above instead.

=item meta()

The C<meta()> method from L<Class::MOP::Class>

=back

=back

=head1 STUFF YOU SHOULD READ

=over 4

=item Note about double fork

Taken from L<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012>
in a comment entitled I<The second fork _is_ necessary by Jonathan Bartlett>,
it is not the definitive statement on the issue, but it's clear and well
written enough so I decided to reproduce it here.

  The first fork accomplishes two things - allow the shell to return,
  and allow you to do a setsid().

  The setsid() removes yourself from your controlling terminal. You
  see, before, you were still listed as a job of your previous process,
  and therefore the user might accidentally send you a signal. setsid()
  gives you a new session, and removes the existing controlling terminal.

  The problem is, you are now a session leader. As a session leader, if
  you open a file descriptor that is a terminal, it will become your
  controlling terminal (oops!). Therefore, the second fork makes you NOT
  be a session leader. Only session leaders can acquire a controlling
  terminal, so you can open up any file you wish without worrying that
  it will make you a controlling terminal.

  So - first fork - allow shell to return, and permit you to call setsid()

  Second fork - prevent you from accidentally reacquiring a controlling
  terminal.

That said, you don't always want this to be the behavior, so you are
free to specify otherwise using the I<no_double_fork> attribute.

=item Note about zombies

Doing the double fork (see above) tends to get rid of your zombies since
by the time you have double forked your daemon process is then owned by
the init process. However, sometimes the double-fork is more than you
really need, and you want to keep your daemon processes a little closer
to you. In this case you have to watch out for zombies, you can avoid then
by just setting the I<ignore_zombies> attribute (see above).

=back

=head1 ENVIRONMENT VARIABLES

These variables are best just used for debugging and/or testing, but
not used for actual logging. For that, you should reopen C<STDOUT>/C<STDERR> on
your own.

=over 4

=item B<MX_DAEMON_STDOUT>

A filename to redirect the daemon C<STDOUT> to.

=item B<MX_DAEMON_STDERR>

A filename to redirect the daemon C<STDERR> to.

=back

=head1 DEPENDENCIES

L<Moose::Role>, L<POSIX>

=head1 INCOMPATIBILITIES

=head1 SEE ALSO

L<Proc::Daemon>

This code is based B<HEAVILY> on L<Proc::Daemon>, we originally
depended on it, but we needed some more flexibility, so instead
we just stole the code.

=head1 SUPPORT

Bugs may be submitted through L<the RT bug tracker|https://rt.cpan.org/Public/Dist/Display.html?Name=MooseX-Daemonize>
(or L<bug-MooseX-Daemonize@rt.cpan.org|mailto:bug-MooseX-Daemonize@rt.cpan.org>).

There is also a mailing list available for users of this distribution, at
L<http://lists.perl.org/list/moose.html>.

There is also an irc channel available for users of this distribution, at
L<C<#moose> on C<irc.perl.org>|irc://irc.perl.org/#moose>.

=head1 AUTHORS

=over 4

=item *

Stevan Little <stevan.little@iinteractive.com>

=item *

Chris Prather <chris@prather.org>

=back

=head1 COPYRIGHT AND LICENCE

This software is copyright (c) 2007 by Chris Prather.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

Portions heavily borrowed from L<Proc::Daemon> which is copyright Earl Hood.

=cut