blib/lib/Data/Tools/Process/Forks.pm untested

filter: Statementstmt 0.0% 0 / 77 Branchbran 0.0% 0 / 28 Conditioncond 0.0% 0 / 9 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 156 CC 15 SCAR 26.0
CC
15
Cov
0%
__wait_count
30.0
forks_start_one
30.0
forks_wait_one
20.0
CRAP 13.5
1 ##############################################################################
2 #
3 # Data::Tools::Process::Forks fork process and control
4 # Copyright (c) 2013-2026 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::Forks;
12 use strict;
13 use Exporter;
14 use POSIX;
15 our $VERSION = '1.60';
16  
17 our @ISA = qw( Exporter );
18 our @EXPORT = qw(
19  
20 forks_set_max
21 forks_get_max
22 forks_set_start_wait_to
23  
24 forks_reset_state
25 forks_setup_signals
26
27 forks_start_one
28 forks_wait_one
29 forks_wait_all
30
31 forks_count
32 forks_signal_all
33 forks_stop_all
34 forks_kill_all
35
36 forks_pids
37 forks_names
38
39 );
40  
41 # TODO: add on fork finish callback
42  
43 my $__MAX_FORKS = 4;
44 my %__FORKS = (); # maps pid to name (name is '*' for no-named-ones)
45 my $__START_WAIT_TO = 0; # wait timeout used when trying to start new fork
46  
47 sub forks_set_max
48 {
49 my $max = @_ == 0 ? __get_max_machine_core_count() : shift;
50
51 $max = 4 if $max < 1; # no foreground option, do not fork in higher-level logic
52
53 $__MAX_FORKS = $max;
54 }
55  
56 sub forks_get_max
57 {
58 return $__MAX_FORKS;
59 }
60  
61 sub forks_set_start_wait_to
62 {
63 my $to = shift;
64
65 $to = 0 if $to < 0;
66
67 $__START_WAIT_TO = $to;
68 }
69  
70 sub __sig_handler_term
71 {
72 forks_stop_all();
73 forks_wait_all();
74 exit 111;
75 };
76  
77 sub forks_setup_signals
78 {
79 $SIG{ 'INT' } = \&__sig_handler_term;
80 $SIG{ 'TERM' } = \&__sig_handler_term;
81 # TODO: $SIG{ 'CHILD' }?
82 }
83  
84 sub forks_reset_state
85 {
86 $__MAX_FORKS = 4;
87 %__FORKS = ();
88 }
89  
90 sub forks_signal_all
91 {
92 my $sig = shift // return undef;
93 # TODO: filter by NAMEs
94  
95 kill( $sig, keys %__FORKS );
96 }
97  
98 sub forks_stop_all
99 {
100 # TODO: filter by NAMEs
101 return forks_signal_all( 'TERM' );
102 }
103  
104 sub forks_kill_all
105 {
106 # TODO: filter by NAMEs
107 return forks_signal_all( 'KILL' );
108 }
109  
110 sub forks_count
111 {
112 # TODO: filter by NAMEs
113 return scalar( keys %__FORKS );
114 }
115  
116 sub __wait_count
117 {
118 my $bar = shift; # wait until forks count fall below this bar (count)
119 my $to = shift; # timeout in seconds, if 0 wait will be blocking
120
121 my $sc = 0; # stopped count
122
123 my $xt = time() + $to if $to; # expire/timeout time
124 while( forks_count() >= $bar ) # should reach below $bar
125 {
126 my $pid = forks_wait_one( $to ); # if $to, will be non-blocking
127 $sc++, next if $pid;
128 last unless forks_count(); # no more processes to wait for, return
129 last if $xt and time() > $xt;
130 sleep( 1 ); # wait 1 second
131 }
132
133 return $sc;
134 }
135  
136 sub forks_wait_one
137 {
138 my $nb = shift;
139
140 my $nb = $nb ? WNOHANG : 0;
141
142 my $pid = waitpid( -1, $nb );
143 return () if $pid <= 0;
144
145 my $status = $?;
146 my $exit = $status >> 8; # exit code
147 my $xsig = $status & 127; # exit signal
148 my $name = $__FORKS{ $pid }; # forked process name
149
150 delete $__FORKS{ $pid };
151  
152 # print " <-- exit ( $pid, $exit, $xsig, $name )\n";
153 # TODO: callback with ( $pid, $exit, $xsig, $name )
154  
155 return wantarray ? ( $pid, $exit, $xsig, $name ) : $pid;
156 }
157  
158 sub forks_wait_all
159 {
160 return __wait_count( 1, @_ ); # wait all
161 }
162  
163 sub forks_start_one
164 {
165 my $name = shift || '*';
166 my $sub = shift;
167  
168 __wait_count( $__MAX_FORKS, $__START_WAIT_TO ); # wait count to fall below max
169 return '0E0' if forks_count() >= $__MAX_FORKS; # __wait_count() was cancelled on timeout
170  
171  
172 my $pid = fork();
173 return '0E0' unless defined $pid; # error, but will still be in the parent
174  
175 if( $pid )
176 {
177 # print "--> forked [$pid]\n";
178 # parent here
179 $__FORKS{ $pid } = $name;
180 return $pid;
181 }
182 else
183 {
184 # print " [$$] here\n";
185 }
186  
187 # child here
188 forks_reset_state(); # allow, forked child's own fork pools
189  
190 exit $sub->( @_ ) if $sub; # exec sub and exit with exit code
191
192 return 0;
193 }
194  
195 sub forks_pids
196 {
197 # TODO: filter by NAMEs
198 return keys %__FORKS;
199 }
200  
201 sub forks_names
202 {
203 my %n;
204 $n{ $_ }++ for values %__FORKS;
205 return keys %n;
206 }
207  
208  
209 sub __get_max_machine_core_count
210 {
211 # only on Linux
212 my $cc = 0;
213 open my $fh, '<', '/proc/cpuinfo';
214 $cc += /^processor\s*:/ for <$fh>;
215 close $fh;
216 return $cc || 8;
217 }
218  
219 1;
220  
221  
222 =pod
223  
224 =head1 NAME
225  
226 Data::Tools::Process::Forks - Fork process creation and control
227  
228 =head1 SYNOPSIS
229  
230 use Data::Tools::Process::Forks;
231  
232 # set up signal handlers for graceful shutdown (optional)
233 forks_setup_signals();
234  
235 # configure maximum concurrent forks (default is 8)
236 forks_set_max( 18 );
237  
238 # case A: start simple worker processes
239 for my $task ( @tasks )
240 {
241 # this is the parent process, fork and continue
242 forks_start_one( 'THINKER' ) and next;
243
244 # here is the forked child process, do some work and exit:
245 # ...
246 exit 111;
247 # exit here is mandatory and omitting it would be a problem,
248 # since it will start forking more processes from the child one!
249 # however it is the most simple use case.
250 }
251  
252 # wait for all children to finish
253 forks_wait_all();
254  
255  
256  
257 # case B: start worker processes with sub reference or closure
258 for my $task ( @tasks )
259 {
260 forks_start_one( 'GOPHER', \&fetch_things );
261 forks_start_one( 'PARSER', sub { call_parser(); cleanup(); } );
262 forks_start_one( undef, sub { print "Testing :)\n; return 222 " } );
263 }
264  
265 # wait for all children to finish
266 forks_wait_all();
267  
268  
269 =head1 DESCRIPTION
270  
271 Data::Tools::Process::Forks provides a simple interface for managing multiple
272 forked child processes. It handles the common patterns of limiting concurrent
273 processes, tracking active children by name, and graceful shutdown via signals.
274  
275 The module keeps track of running and completed children when the maximum fork
276 count is reached, allowing new processes to start or wait for new open slot.
277  
278 =head1 FUNCTIONS
279  
280 All functions are exported by default.
281  
282 =head2 Signal Handling
283  
284 =head3 forks_setup_signals()
285  
286 Installs signal handlers for C<INT> and C<TERM> signals. When either signal is
287 received, the handler will send C<TERM> to all child processes, wait for them
288 to exit, then terminate the parent process with exit code 111.
289  
290 forks_setup_signals();
291  
292 This is optional and should typically be called early in the parent process
293 before forking any children.
294  
295 =head2 Process Creation and Waiting
296  
297 =head3 forks_start_one( $name, $coderef, @args )
298  
299 Forks a new child process to execute the given subroutine.
300  
301 my $pid = forks_start_one( 'worker', \&do_work, @work_args );
302  
303 B<Parameters:>
304  
305 =over 4
306  
307 =item C<$name>
308  
309 Optional name for the forked process, used for identification. Defaults to
310 C<'*'> if not provided or undefined.
311  
312 =item C<$coderef>
313  
314 Optional code reference to execute in the child. If provided, the child will
315 execute this subroutine and exit with its return value as the exit code.
316 If not provided, the function returns 0 in the child, allowing inline child
317 code (see SYNOPSIS).
318  
319 =item C<@args>
320  
321 Optional arguments passed to C<$coderef> when executed in the child.
322  
323 =back
324  
325 B<Returns:>
326  
327 =over 4
328  
329 =item *
330  
331 In the parent: the child's PID on success, or C<'0E0'> (true but zero) on
332 fork failure. On fork failure and inline child prcesses, the parent will simply
333 skip the child code and try to fork again. To avoid high load, save the result
334 code and do something like:
335  
336  
337 my $fr = forks_start_one();
338 if( $fr eq '0E0' )
339 {
340 print "fork error [$!] sleeping\n";
341 sleep 3;
342 }
343 next if $fr;
344
345 # forked child here
346 exit 1;
347  
348 =item *
349  
350 In the child (when no C<$coderef> provided): 0
351  
352 To be sure code runs in the forked child process, return value must be checked
353 like this:
354  
355 if( ! forks_start_one() )
356 {
357 # child here
358 # must finish with exit!
359 exit 2;
360 }
361  
362 WARNING: return value should never be compared to 0, otherwise on fork errors,
363 child code will be executed in the parent process!
364  
365 if( forks_start_one() == 0 )
366 {
367 # WRONG! this will execute in the parent
368 # must finish with exit!
369 exit 2;
370 }
371
372  
373 =back
374  
375 B<Note:> If the current number of active forks equals or exceeds the maximum
376 (see C<forks_set_max()>), this function blocks until a child exits before
377 forking the new process.
378  
379 =head3 forks_wait_one( $non_blocking )
380  
381 Waits for one child process to exit.
382  
383 # blocking, return all child attributes (list context)
384 my ( $pid, $exit_code, $signal, $name ) = forks_wait_one();
385
386 # Non-blocking check, got pid only (scalar context)
387 my $pid = forks_wait_one( 1 );
388  
389 B<Parameters:>
390  
391 =over 4
392  
393 =item C<$non_blocking>
394  
395 If true, returns immediately if no child has exited (uses C<WNOHANG>).
396 If false or omitted, blocks until a child exits.
397  
398 =back
399  
400 B<Returns:>
401  
402 In list context: C<( $pid, $exit_code, $signal, $name )>
403  
404 =over 4
405  
406 =item C<$pid>
407  
408 The process ID of the exited child.
409  
410 =item C<$exit_code>
411  
412 The exit code returned by the child (high 8 bits of C<$?>).
413  
414 =item C<$signal>
415  
416 The signal that terminated the child, if any (low 7 bits of C<$?>).
417  
418 =item C<$name>
419  
420 The name assigned to the child when it was forked.
421  
422 =back
423  
424 In scalar context: returns only C<$pid>.
425  
426 Returns an empty list if no children have exited (non-blocking mode) or if
427 there are no active children.
428  
429 =head3 forks_wait_all( $timeout )
430  
431 Blocks until all active child processes have exited. Optional timeout in
432 seconds can be specified to avoid blocking. Avoiding blocking may give control
433 to the parent process when forked one has blocked for some reason.
434  
435 # block until all forks finished
436 forks_wait_all();
437
438 # or
439
440 # wait 4 seconds for finished forks and return finished count
441 my $c = forks_wait_all( 4 );
442
443  
444 internally it calls forks_wait_one() until internal forked processes
445 count reached 0 or timeout reached.
446  
447 =head2 Process Signalling
448  
449 =head3 forks_signal_all( $signal )
450  
451 Sends the specified signal to all active child processes.
452  
453 forks_signal_all( 'HUP' );
454 forks_signal_all( 15 ); # SIGTERM by number
455  
456 if signal is undef or empty parameter list, will do nothing and exit.
457  
458 B<Parameters:>
459  
460 =over 4
461  
462 =item C<$signal>
463  
464 The signal name or number to send.
465  
466 =back
467  
468 B<Returns:> C<undef> if no signal specified, otherwise the result of C<kill()>.
469  
470 =head3 forks_stop_all()
471  
472 Sends C<TERM> signal to all active child processes.
473  
474 forks_stop_all();
475  
476 Equivalent to C<forks_signal_all( 'TERM' )>.
477  
478 =head3 forks_kill_all()
479  
480 Sends C<KILL> signal to all active child processes.
481  
482 forks_kill_all();
483  
484 Equivalent to C<forks_signal_all( 'KILL' )>. Use this for forceful termination
485 when children do not respond to C<TERM>.
486  
487 =head2 Configuration
488  
489 =head3 forks_set_max( $max )
490  
491 Sets the maximum number of concurrent child processes (slots).
492  
493 forks_set_max( 16 );
494
495 B<Parameters:>
496  
497 =over 4
498  
499 =item C<$max>
500  
501 Maximum number of concurrent forks. Values less than 1 are clamped to 4.
502  
503 =back
504  
505 When C<forks_start_one()> is called and the current fork count (slots) equals
506 or exceeds this maximum, it will wait until a child exits before forking.
507  
508 Default value is 4.
509  
510 If called without parameters, will try to figure machine core count and set
511 it the same. Note that this works only on machines with /proc file system
512 (i.e. Linux). if not Linux, /proc not mounted or other error will set to 8.
513  
514 =head3 forks_get_max()
515  
516 Returns the current maximum fork limit.
517  
518 my $max = forks_get_max();
519  
520 =head2 Inspection
521  
522 =head3 forks_count()
523  
524 Returns the number of currently active child processes.
525  
526 my $active = forks_count();
527 print "Running $active workers\n";
528  
529 =head3 forks_pids()
530  
531 Returns a list of PIDs for all active child processes.
532  
533 my @pids = forks_pids();
534  
535 =head3 forks_names()
536  
537 Returns a list of unique names assigned to active child processes.
538  
539 my @names = forks_names();
540  
541 Note that multiple processes may share the same name; this returns only
542 unique names in use.
543  
544 =head3 forks_set_start_wait_to( $timeout )
545  
546 This sets timeout for waiting for free slot when trying to start new fork but
547 maximum count has been reached. Setting $timeout to 0 will enable blocking,
548 i.e. forks_start_one() will wait until slot freed. If timeout reached
549 forks_start_one() will return '0E0' (zero but true) which is same as fork
550 error.
551  
552 =head1 EXAMPLES
553  
554 =head2 Parallel Task Processing
555  
556 use Data::Tools::Process::Forks;
557  
558 forks_setup_signals();
559 forks_set_max( 6 );
560  
561 my @files = glob( '*.dat' );
562  
563 for my $file ( @files )
564 {
565 forks_start_one(
566 'processor',
567 sub
568 {
569 process_file( $file );
570 return 0;
571 }
572 );
573 }
574  
575 forks_wait_all();
576 print "All files processed\n";
577  
578 =head2 Worker Pool with Status Monitoring
579  
580 use Data::Tools::Process::Forks;
581  
582 forks_setup_signals();
583 forks_set_max( 11 );
584  
585 # Start workers
586 for my $id ( 1 .. 20 )
587 {
588 forks_start_one( "worker-$id", \&worker_task, $id );
589 }
590  
591 # Monitor progress
592 while( forks_count() > 0 )
593 {
594 my ( $pid, $exit, $sig, $name ) = forks_wait_one();
595 if( $exit == 0 )
596 {
597 print "$name completed successfully\n";
598 }
599 else
600 {
601 print "$name failed with exit code $exit\n";
602 }
603 }
604  
605 =head2 Graceful Shutdown
606  
607 use Data::Tools::Process::Forks;
608  
609 forks_setup_signals(); # Handles INT/TERM automatically
610  
611 # Or manual shutdown:
612 END
613 {
614 if( forks_count() > 0 )
615 {
616 print "Shutting down workers...\n";
617 forks_stop_all();
618 forks_wait_all();
619 }
620 }
621  
622 =head1 NOTES
623  
624 =over 4
625  
626 =item *
627  
628 The module uses package-level variables to track state. Only one fork pool
629 can be managed per process but fork names can represent separate fork pools.
630  
631 This is really a design choice. This module was meant to be simple with
632 minimum dependencies (only Perl core Exporter and POSIX).
633  
634 For, possibly, more complex things you may check B<Parralel::ForkManager>
635 on B<CPAN>.
636  
637 =item *
638  
639 Child processes reset the parent fork pool state so they can have own
640 fork process pool and use this module themselves.
641  
642 =item *
643  
644 The C<forks_start_one()> function may block indefinitely if child processes
645 do not exit and the maximum fork count is reached. To avoid this situation
646 C<forks_set_start_wait_to()> can be used to set timeout for waiting for a free
647 slot to be available while trying to start new one:
648  
649 forks_set_start_wait_to( 4 );
650 my $fr = forks_start_one();
651 if( $fr eq '0E0' )
652 {
653 # either fork error occured
654 # or timeout waiting for free slot reached
655 ...
656 }
657  
658 =back
659  
660 =head1 SEE ALSO
661  
662 L<Parallel::ForkManager>, L<fork(2)>, L<waitpid(2)>, L<POSIX>
663  
664 =head1 AUTHOR
665  
666 Vladi Belperchinov-Shabanski "Cade"
667 <cade@noxrun.com> <cade@bis.bg> <cade@cpan.org>
668 http://cade.noxrun.com/
669  
670 =head1 COPYRIGHT AND LICENSE
671  
672 Copyright (c) 2013-2026 Vladi Belperchinov-Shabanski "Cade"
673  
674 This program is free software; you can redistribute it and/or modify it
675 under the terms of the GNU General Public License as published by the
676 Free Software Foundation; either version 2 of the License, or (at your
677 option) any later version.
678  
679 =cut