lib/Data/Tools/Process.pm

filter: Statementstmt 60.7% 48 / 79 Branchbran 26.0% 13 / 50 Conditioncond 33.3% 5 / 15 MC/DCmcdc 25.0% 2 / 8 Subroutinesub 81.8% 9 / 11 Podpod 100% 6 / 6 totaltotal 49.1% 83 / 169 CC 34 SCAR 54.1
CC
34
Cov
46%
daemonize
462.0
pidfile_create
6.0
daemonize_here
6.0
CRAP 222.6
↑ Summary blib/lib/Data/Tools/Process/ForkPool.pm »
1 ##############################################################################
2 #
3 # Data::Tools::Process process control and utilities
4 # Copyright (c) 2013-2024 Vladi Belperchinov-Shabanski "Cade"
5 # <cade@noxrun.com> <cade@bis.bg> <cade@cpan.org>
6 # http://cade.noxrun.com/
7 #
8 # GPL
9 #
10 ##############################################################################
11 package Data::Tools::Process;
12 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 4 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 4 ▶use Cwd;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 4 ▶use POSIX;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 4 ▶use Data::Tools;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 4 our $VERSION = '1.60';
20  
21 4 our @ISA = qw( Exporter );
22 4 our @EXPORT = qw(
23 fork_exec_cmd
24 daemonize
25 daemonize_here
26  
27 pidfile_kill_and_remove
28 pidfile_create
29 pidfile_remove
30 );
31  
32 ##############################################################################
33  
34 sub fork_exec_cmd
35 4 ▶{
Subroutine fork_exec_cmd: called CC=3 SCAR=11.2
Pod documented
36 4 my $cmd = shift;
37  
38 4 my $pid = fork();
39 4 ▶ return undef if ! defined $pid; # fork failed
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 4 4
40 4 ▶ return $pid if $pid; # master process here
Branch: 1 branch
BranchTrueFalseTotal
if $pid 3 1 4
41 1 exec $cmd; # sub process here
42 0 exit; # if sub exec fails...
43 }
44  
45 ##############################################################################
46  
47 # TODO:
48 # pidfile
49 # lock pidfile to ensure single process
50 #
51  
52 sub daemonize
53 0 ▶{
Subroutine daemonize: not called CC=21 SCAR=61.4
Pod documented
54 0 my %opt = @_;
55  
56 0 hash_uc_ipl( \%opt );
57  
58 0 ▶ umask( $opt{ 'UMASK' } // 0077 );
Condition0%0/2
$opt{"UMASK"} // 63
l!l
00
MC/DC0%0/1
$opt{"UMASK"} // 63
$opt{"UMASK"}
Truth table0%0/2
A
A= $opt{"UMASK"}
Aresult
11
00
59  
60 0 my $pid = fork();
61 0 ▶ die "fatal: daemonize: fork step 1 failed due to {$!}\n" unless defined $pid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 0 0
62 0 ▶ POSIX::_exit( 0 ) if $pid; # avoid END{} and all destructors
Branch: 1 branch
BranchTrueFalseTotal
if $pid 0 0 0
63  
64 0 ▶ POSIX::setsid() or die "fatal: daemonize: cannot detach controlling process/terminal due to {$!}\n";
Branch: 1 branch
BranchTrueFalseTotal
POSIX::setsid() or die "fatal: daemonize: cannot detach controlling process/terminal due to {$!}\n" 0 0 0
65  
66 # SVR4-second-fork policy
67 0 $pid = fork();
68 0 ▶ die "fatal: daemonize: fork final step failed: $!\n" unless defined $pid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 0 0
69 0 ▶ POSIX::_exit( 0 ) if $pid; # avoid END{} and all destructors
Branch: 1 branch
BranchTrueFalseTotal
if $pid 0 0 0
70  
71 0 ▶ my $chdir = $opt{ 'CHDIR' } // '/';
Condition0%0/2
$opt{"CHDIR"} // "/"
l!l
00
MC/DC0%0/1
$opt{"CHDIR"} // "/"
$opt{"CHDIR"}
Truth table0%0/2
A
A= $opt{"CHDIR"}
Aresult
11
00
72 0 ▶ chdir( $chdir ) or die "fatal: daemonize: cannot chdir to [$chdir] due to {$!}\n";
Branch: 1 branch
BranchTrueFalseTotal
chdir $chdir or die "fatal: daemonize: cannot chdir to [$chdir] due to {$!}\n" 0 0 0
73  
74 # close stdio perl handles first, otherwise perl reopens a std handle on
75 # the fd number it had before, which may not be its 0/1/2
76 0 close( STDIN );
77 0 close( STDOUT );
78 0 close( STDERR );
79  
80 # free fds 0/1/2 (any handle may hold them), so the reopened stdio gets
81 # them, close all other fds only if requested:
82 # CLOSE_ALL_FDS == 1 closes up to _SC_OPEN_MAX but not above 1024 (it can be
83 # huge under high ulimit and the loop gets slow), 2..1024 -- uncapped,
84 # above 1024 -- the value itself is the cap
85 0 my $closemax = 3;
86 0 ▶ if( my $close_all = $opt{ 'CLOSE_ALL_FDS' } )
Branch: 1 branch
BranchTrueFalseTotal
if (my $close_all = $opt{"CLOSE_ALL_FDS"}) 0 0 0
87 {
88 0 $closemax = POSIX::sysconf( &POSIX::_SC_OPEN_MAX );
89 0 ▶ $closemax = 1024 if $closemax <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $closemax <= 0 0 0 0
90 0 ▶ my $cap = $close_all == 1 ? 1024 : $close_all > 1024 ? $close_all : undef;
Branch: 2 branches
BranchTrueFalseTotal
$close_all == 1 ? : 0 0 0
$close_all > 1024 ? : 0 0 0
91 0 ▶ $closemax = $cap if $cap and $closemax > $cap;
Branch: 1 branch
BranchTrueFalseTotal
if $cap and $closemax > $cap 0 0 0
Condition0%0/3
$cap and $closemax > $cap
!ll&&!rl&&r
000
MC/DC0%0/2
$cap and $closemax > $cap
$cap $closemax > $cap
Truth table0%0/3
A and B
A= $capB= $closemax > $cap
ABresult
0X0
100
111
92 }
93 0 POSIX::close( $_ ) for 0 .. $closemax - 1;
94  
95 0 ▶ my ( $out_mode, $out_file ) = defined $opt{ 'STDOUT' } ? ( '>>', $opt{ 'STDOUT' } ) : ( '+>&', 'STDIN' );
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'STDOUT'} ? : 0 0 0
96 0 ▶ my ( $err_mode, $err_file ) = defined $opt{ 'STDERR' } ? ( '>>', $opt{ 'STDERR' } ) : ( '+>&', 'STDIN' );
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'STDERR'} ? : 0 0 0
97  
98 # reopen stdio, open() takes the lowest free fd, so the order here gives
99 # STDIN=0, STDOUT=1, STDERR=2, which C code and child processes expect.
100 # STDOUT/STDERR files are appended, relative names are under CHDIR
101 0 ▶ open( STDIN, '+>', '/dev/null' ) or die "fatal: daemonize: cannot reopen STDIN to [/dev/null] due to {$!}\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDIN, "+>", "/dev/null" or die "fatal: daemonize: cannot reopen STDIN to [/dev/null] due to {$!}\n" 0 0 0
102 0 ▶ open( STDOUT, $out_mode, $out_file ) or die "fatal: daemonize: cannot reopen STDOUT to ($out_mode $out_file) in [$chdir] due to {$!}\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDOUT, $out_mode, $out_file or die "fatal: daemonize: cannot reopen STDOUT to ($out_mode $out_file) in [$chdir] due to {$!}\n" 0 0 0
103 0 ▶ open( STDERR, $err_mode, $err_file ) or die "fatal: daemonize: cannot reopen STDERR to ($err_mode $err_file) in [$chdir] due to {$!}\n";
Branch: 1 branch
BranchTrueFalseTotal
open STDERR, $err_mode, $err_file or die "fatal: daemonize: cannot reopen STDERR to ($err_mode $err_file) in [$chdir] due to {$!}\n" 0 0 0
104  
105 0 return 1;
106 }
107  
108 sub daemonize_here
109 0 ▶{
Subroutine daemonize_here: not called CC=2 SCAR=17.9
Pod documented
110 0 ▶ my $cwd = getcwd() // die "cannot get current working directory\n";
Condition0%0/2
getcwd() // die("cannot get current working directory\n")
l!l
00
MC/DC0%0/1
getcwd() // die("cannot get current working directory\n")
getcwd()
Truth table0%0/2
A
A= getcwd()
Aresult
11
00
111 0 return daemonize( CHDIR => $cwd, @_ );
112 }
113  
114 ##############################################################################
115  
116 # pidfile_kill_and_remove( $pid_file_name, signal_list... )
117 # args:
118 # $pid_file_name -- file name of the pid file
119 # signal_list -- list of signals to be sent to the pidfile's pid
120 # if value has 's' at the end it is considered sleep time
121 # in seconds between the signals. all are executed in the
122 # given order:
123 # 15, 5s, 15, 2s, 9 -- send two TERM signals with 5 seconds
124 # sleep and then wait 2 seconds and send KILL
125 # returns:
126 # * undef if $pid_file_name does not exist
127 # * 1 if signals has been sent and $pid_file_name file removed
128  
129 sub pidfile_kill_and_remove
130 3 ▶{
Subroutine pidfile_kill_and_remove: called CC=5 SCAR=16.2
Pod documented
131 3 my $fname = shift;
132 3 my @siglist = @_;
133  
134 3 ▶ return undef unless -e $fname;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $fname 2 1 3
135  
136 1 ▶ @siglist = ( 15 ) unless @siglist;
Branch: 1 branch
BranchTrueFalseTotal
unless @siglist 0 1 1
137  
138 1 my $opid = int( file_load( $fname ) );
139  
140 1 for( @siglist )
141 {
142 1 ▶ sleep( $_ ), next if s/s$//;
Branch: 1 branch
BranchTrueFalseTotal
if s/s$// 0 1 1
143 1 kill( $_, $opid );
144 }
145  
146 1 unlink( $fname );
147  
148 1 return 1;
149 }
150  
151 # pidfile_create( $pid_file_name, STALE_CHECK => 1 )
152 # STALE_CHECK is optional and will try to check if existing process is
153 # running with the same pid file name
154 #
155 # returns:
156 # * undef for success
157 # * negative for error
158 # * positive (non-zero) for existing running process pid
159 # errors:
160 # * -1 cannot create pidfile or was created just before we try
161  
162 sub pidfile_create
163 15 ▶{
Subroutine pidfile_create: called CC=6 SCAR=18.0
Pod documented
164 15 my $fname = shift;
165 15 my %opt = @_;
166  
167 15 hash_uc_ipl( \%opt );
168  
169 15 my $opid = int( file_load( $fname ) );
170 15 ▶ unlink( $fname ) if ( $opid < 1 ) or ( $opt{ 'STALE_CHECK' } and ! kill( 0, $opid ) );
Branch: 1 branch
BranchTrueFalseTotal
if $opid < 1 or $opt{"STALE_CHECK"} and not kill(0, $opid) 10 5 15
Condition83%5/6
$opid < 1 or $opt{"STALE_CHECK"} and not kill(0, $opid)
l!l&&r!l&&!r
825
$opt{"STALE_CHECK"} and not kill(0, $opid)
!ll&&!rl&&r
502
MC/DC66%2/3
$opid < 1 or $opt{"STALE_CHECK"} and not kill(0, $opid)
$opid < 1 $opt{"STALE_CHECK"} not kill(0, $opid)
Truth table75%3/4
A or B and not(C)
A= $opid < 1B= $opt{"STALE_CHECK"}C= not kill(0, $opid)
ABCresult
1XX1
0111
00X0
0100
171  
172 15 ▶ return $opid if -e $fname;
Branch: 1 branch
BranchTrueFalseTotal
if -e $fname 5 10 15
173  
174 10 dir_path_ensure( file_path( $fname ) );
175 10 ▶ return -1 unless sysopen my $fh, $fname, O_CREAT | O_EXCL | O_RDWR, 0600;
Branch: 1 branch
BranchTrueFalseTotal
unless sysopen my $fh, $fname, 194, 384 0 10 10
176  
177 10 print $fh $$;
178  
179 10 close $fh;
180  
181 10 return undef;
182 }
183  
184 sub pidfile_remove
185 10 ▶{
Subroutine pidfile_remove: called CC=2 SCAR=7.1
Pod documented
186 10 my $fname = shift;
187  
188 10 ▶ unlink( $fname ) if $fname;
Branch: 1 branch
BranchTrueFalseTotal
if $fname 10 0 10
189 10 return undef;
190 }
191  
192  
193 ##############################################################################
194  
195 =pod
196  
197  
198 =head1 NAME
199  
200 Data::Tools::Process provides set of functions for process control,
201 forking, daemonizing and pid files handling.
202  
203 =head1 SYNOPSIS
204  
205 use Data::Tools::Process qw( :all ); # import all functions
206 use Data::Tools::Process; # the same as :all :)
207 use Data::Tools::Process qw( :none ); # do not import anything
208  
209 # --------------------------------------------------------------------------
210  
211 # fork and exec a command, returns the child pid to the parent
212 my $pid = fork_exec_cmd( "/usr/bin/somecmd --with args" );
213 waitpid( $pid, 0 );
214  
215 # --------------------------------------------------------------------------
216  
217 # detach from the controlling terminal and become a daemon
218 daemonize();
219 daemonize( CHDIR => '/var/lib/myapp', UMASK => 0022 );
220 daemonize( STDOUT => '/var/log/myapp.log', STDERR => '/var/log/myapp.err' );
221 daemonize( CLOSE_ALL_FDS => 1 );
222  
223 # the same, but stay in the current directory
224 daemonize_here( STDOUT => 'myapp.log', STDERR => 'myapp.log' );
225  
226 # --------------------------------------------------------------------------
227  
228 # create a pid file, holding the pid of the current process
229 my $res = pidfile_create( '/var/run/myapp.pid' );
230 die "already running with pid [$res]" if $res;
231  
232 # ...and take over the pid file if the process in it is gone
233 my $res = pidfile_create( '/var/run/myapp.pid', STALE_CHECK => 1 );
234  
235 # signal the process named in a pid file and remove the file
236 pidfile_kill_and_remove( '/var/run/myapp.pid' ); # sends TERM
237 pidfile_kill_and_remove( '/var/run/myapp.pid', 15, '5s', 9 );
238  
239 # just remove the pid file
240 pidfile_remove( '/var/run/myapp.pid' );
241  
242 # --------------------------------------------------------------------------
243  
244 =head1 FUNCTIONS
245  
246 =head2 fork_exec_cmd( $command )
247  
248 Forks and exec()s $command in the child process.
249  
250 Returns:
251  
252 * the child process pid in the parent process
253 * undef if fork() failed
254  
255 The child never returns. $command is passed to exec() as a single string,
256 so it is subject to the usual shell handling of exec().
257  
258 =head2 daemonize( %options )
259  
260 Detaches the current process from the controlling terminal and turns it into
261 a daemon: forks, calls POSIX::setsid(), forks again (SVR4 second fork policy),
262 changes the current directory, closes STDIN, STDOUT and STDERR (and all other
263 open file descriptors if CLOSE_ALL_FDS is set) and reopens them as file
264 descriptors 0, 1 and 2. STDIN is always /dev/null, STDOUT and STDERR are
265 /dev/null unless files are given for them.
266  
267 Options are:
268  
269 CHDIR => $path # directory to change to, default is '/'
270 UMASK => $umask # umask to set, default is 0077
271 STDOUT => $file # file for STDOUT, default is /dev/null
272 STDERR => $file # file for STDERR, default is /dev/null
273 CLOSE_ALL_FDS => 1 # close all open file descriptors, default is
274 # to close only 0, 1 and 2, see below
275  
276 STDOUT and STDERR files are opened for append and created if missing, with
277 permissions limited by UMASK (0600 with the default). Relative file names
278 are resolved after the change to CHDIR, so with the default CHDIR '/'
279 use full paths (or daemonize_here()). STDOUT and STDERR may name the same
280 file. STDOUT is buffered, set autoflush on it if log lines must show up
281 immediately.
282  
283 CLOSE_ALL_FDS => 1 closes file descriptors up to the system limit
284 (sysconf _SC_OPEN_MAX), but not above 1024, since under a high open files
285 limit (ulimit -n) closing them one by one can take a long time. A value
286 from 2 to 1024 (e.g. CLOSE_ALL_FDS => 2) closes up to the system limit
287 uncapped. A value above 1024 is used as the cap instead of 1024, e.g.
288 CLOSE_ALL_FDS => 65536 closes up to the system limit, but not above 65536.
289  
290 Returns 1 in the resulting daemon process. The original process and the
291 intermediate one leave with POSIX::_exit(0) and never return, so END blocks
292 and object destructors are not run in them (they run only in the daemon,
293 when it exits). Dies on any of the steps failing.
294  
295 NOTE: the original process exits (with status 0) before STDOUT/STDERR
296 files are opened, and STDERR is already closed when they are, so a
297 bad STDOUT or STDERR file name (missing directory, no permissions)
298 makes the daemon die() silently: nothing is printed anywhere and
299 the caller sees success. check that the files can be opened before
300 calling daemonize(), for example open them for append and close
301 them, using the same names as they will be resolved after CHDIR.
302  
303 NOTE: without CLOSE_ALL_FDS all file descriptors other than 0, 1 and 2 are
304 inherited by the daemon, close the ones it must not hold (pipes,
305 locks, sockets). with CLOSE_ALL_FDS all open file descriptors are
306 closed, including any files, sockets or database handles opened
307 before the call, and perl handles to them must not be used anymore.
308  
309 =head2 daemonize_here( %options )
310  
311 The same as daemonize() but the CHDIR default is the current working
312 directory instead of '/', so the daemon stays where it was started and
313 relative STDOUT/STDERR file names are relative to it. All daemonize()
314 options are accepted, an explicit CHDIR overrides the default.
315  
316 =head2 pidfile_create( $pid_file_name, %options )
317  
318 Creates $pid_file_name and writes the pid of the current process in it. The
319 file is created with O_EXCL, so two processes racing for the same pid file
320 cannot both succeed. Missing directories on the way are created.
321  
322 Options are:
323  
324 STALE_CHECK => 1 # take over the pid file if its process is not running
325  
326 Returns:
327  
328 * undef on success, the pid file now holds our pid
329 * a positive pid if the pid file exists and holds a running process
330 * -1 if the pid file cannot be created
331  
332 A pid file which does not hold a valid (positive) pid is always considered
333 stale and is replaced, regardless of STALE_CHECK.
334  
335 =head2 pidfile_kill_and_remove( $pid_file_name, @signal_list )
336  
337 Sends the given signals to the pid found in $pid_file_name and then removes
338 the file. @signal_list defaults to a single TERM (15).
339  
340 A list item ending with 's' is not a signal but a sleep time in seconds. All
341 items are processed in the given order, so:
342  
343 pidfile_kill_and_remove( $fname, 15, '5s', 15, '2s', 9 );
344  
345 sends TERM, waits 5 seconds, sends TERM again, waits 2 seconds, sends KILL.
346  
347 Returns:
348  
349 * undef if $pid_file_name does not exist
350 * 1 if the signals have been sent and the pid file removed
351  
352 =head2 pidfile_remove( $pid_file_name )
353  
354 Removes $pid_file_name. Returns undef.
355  
356 =head1 REQUIRED MODULES
357  
358 Data::Tools::Process uses:
359  
360 * POSIX
361 * Data::Tools
362  
363 =head1 GITHUB REPOSITORY
364  
365 git@github.com:cade-vs/perl-data-tools-process.git
366  
367 git clone git://github.com/cade-vs/perl-data-tools-process.git
368  
369 =head1 AUTHOR
370  
371 Vladi Belperchinov-Shabanski "Cade"
372 <cade@noxrun.com> <cade@bis.bg> <cade@cpan.org>
373 http://cade.noxrun.com/
374  
375  
376 =cut
377  
378 ##############################################################################
379 4 1;
↑ Summary blib/lib/Data/Tools/Process/ForkPool.pm »