NAME

Data::Tools::Process::ForkPool - pools of forked processes with messaging

SYNOPSIS

use Data::Tools::Process::ForkPool;
use Time::HiRes qw( sleep );

# supervisor main loop
while( ! $STOP )
  {
  # reap exited, read states, keep 2..16 workers, grow by 2 when all busy
  fpool_manage( 'WORKERS', \&worker, 2, 16, 2, @worker_args );

  for my $pid ( @pids_of_interest )
    {
    my $msg;
    while( fpool_recv_from( 'WORKERS', $pid, \$msg ) )
      {
      # one message from $pid in $msg
      }
    }
  sleep( 0.1 );
  }
fpool_stop_all( 'WORKERS' );

# forked worker
sub worker
{
  $SIG{ 'TERM' } = 'DEFAULT';
  fpool_iam_idle();
  while( 1 )
    {
    my $job;
    my $res = fpool_recv_super( \$job );
    return 0 unless defined $res; # supervisor gone
    if( ! $res ) { sleep( 0.1 ); next } # nothing yet
    fpool_iam_busy();
    fpool_send_super( "done: $job" );
    fpool_iam_idle();
    }
}

DESCRIPTION

A fork pool is a named set of forked processes running the same sub. The supervisor keeps the pool between a minimum and a maximum count and grows it when all forked processes report busy. Each forked process is connected to the supervisor by its own Net::Tools::Socket::Pair socket, used for messages both ways and for the busy/idle state.

Pool names are case insensitive (upper cased). There may be many pools in one supervisor, and a forked process may run its own (nested) pools.

All forked processes of a pool are placed in the pool's own process group, which is used to reap and signal them. See the NOTES below and at the top of the module source for the rules this implies (no setpgrp() or setsid() in forked processes, no other fork()/wait() code in the supervisor, no $SIG{ 'CHLD' } = 'IGNORE', signals are not propagated, etc.).

All functions are exported by default. Functions return undef on errors like an unknown pool or pid. They do not set or clear $SOCK_ERR; it is set only by the Net::Tools::Socket::Pair calls they make, so check it only after a socket call result (0 or undef from send/recv).

MESSAGES

Messages are byte strings up to $Net::Tools::Socket::Pair::MSG_MAX (128 KiB) long, sent and received whole. Data structures must be serialized first. The messages "STATE:*" and "STATE:-" are reserved for fpool_iam_busy() and fpool_iam_idle().

Messages from forked processes are read by fpool_update_state() (called by fpool_manage()) into a per-process queue, from which fpool_recv_from() returns them. Messages to forked processes are read directly by fpool_recv_super().

$Data::Tools::Process::ForkPool::MSG_QUEUE_MAX limits each queue, 0 (the default) means no limit. When a queue is full, its oldest messages are discarded.

SUPERVISOR FUNCTIONS

fpool_manage( $pool, \&sub, $min, $max, $step, @args )

Creates the pool if needed, reaps exited processes (fpool_wait_all()), reads states and messages (fpool_update_state()) and then forks new processes running \&sub->( @args ):

* up to $min, at least $step at a time
* $step more, if all processes are busy and the count is below $max

$min defaults to 0, $max to $min (also when smaller than $min), $step to int( $max / 10 ) + 1. The count may overshoot $max by up to $step - 1.

Should be called periodically from the supervisor's main loop. Returns the count of new processes, or undef if \&sub is not a code reference.

fpool_fork_one( $pool, \&sub, @args )

Forks one process in the pool, creates the pool if needed. Returns the new pid in the supervisor, undef on error. Use it instead of fpool_manage() for an own growing policy, with fpool_wait_one(), fpool_update_state(), fpool_count() and fpool_busy_count().

The forked process never returns from it: it runs \&sub->( @args ) and exits with its return value. If \&sub dies, the error is printed to STDERR and it exits with 255. exit() runs END blocks and destructors in the forked process too.

fpool_wait_all( $pool )

Reaps all already exited processes of the pool, does not block. Returns the count of reaped processes, undef if none were reaped or there is no such pool. Unread messages of a reaped process are discarded.

fpool_wait_one( $pool )

Reaps one already exited process of the pool, does not block. Returns its pid, or in list context ( $pid, $exit_code, $signal, $status ), where $status is the raw wait status ($?, with the core dump flag). Returns undef (empty list) if none exited or there is no such pool.

fpool_update_state( $pool )

Reads pending messages from the forked processes without waiting, up to 8 per process per call, the rest are read on the next call. "STATE:*" and "STATE:-" update the busy state of the process, other messages are queued for fpool_recv_from(). Returns the busy count (0 for a pool which has not forked yet), or undef if there is no such pool.

fpool_count( $pool ) / fpool_busy_count( $pool )

Return the count of processes in the pool and how many of them are busy, as of the last fpool_update_state(). undef if there is no such pool.

fpool_stats( $pool )

Returns a text report: pool name, busy and process counts and the busy state ('*' busy, '-' idle) of each pid. undef if there is no such pool.

fpool_signal_all( $pool, $signal )

Sends $signal ('TERM', 'HUP', 9, etc.) to all processes of the pool (its process group). Returns the result of kill(), undef if there is no such pool or it has no processes.

fpool_stop_all( $pool ) sends TERM, fpool_kill_all( $pool ) sends KILL.

fpool_send_to( $pool, $pid, $data )

Sends message $data to the forked process $pid. Returns the socketpair_send() result: 1 sent, 0 not sent (queue full, etc.), undef if the process closed its socket, or undef if there is no such pool or pid.

fpool_recv_from( $pool, $pid, \$data )

Takes the next queued message from the forked process $pid into $data. Returns 1 for a message, 0 if the queue is empty, undef if there is no such pool or pid. $data is set to undef whenever the result is not 1. Dies (boom) if \$data is not a scalar reference. Messages are queued only by fpool_update_state() (and fpool_manage()).

FORKED PROCESS FUNCTIONS

These work only in a process forked by fpool_fork_one() or fpool_manage(), elsewhere they return undef.

fpool_send_super( $data )

Sends message $data to the supervisor. Returns the socketpair_send() result: 1 sent, 0 not sent, undef if the supervisor is gone.

fpool_recv_super( \$data )

Reads the next message from the supervisor into $data, does not wait. Returns the socketpair_recv() result: 1 for a message, 0 if nothing is waiting, undef if the supervisor is gone.

fpool_iam_busy() / fpool_iam_idle()

Report the busy or idle state to the supervisor, as seen by fpool_busy_count() and used by fpool_manage() to grow the pool.

NOTES

  • Forked processes must not change their process group (setpgrp(), setsid(), daemonizing), otherwise the pool never reaps or signals them.

  • The pools should be the only means of forking in the supervisor. Other code which calls wait() or waitpid( -1, ... ), and $SIG{ 'CHLD' } = 'IGNORE', may reap the pool's processes behind its back. system(), qx// and piped open() are safe.

  • Signals are not propagated to the pools. The supervisor must catch the signals it cares about and call fpool_signal_all(), fpool_stop_all() or fpool_kill_all() for each pool. Forked processes inherit the supervisor's %SIG and should set their own handlers first.

  • If the supervisor dies without stopping the pools, forked processes keep running. They see it as undef from fpool_recv_super() or a getppid() change.

  • Messages sent by a forked process right before it exits may be lost when it is reaped. A process which must deliver a result should wait for an acknowledge from the supervisor before it returns.

  • Inherited DBI handles should have AutoInactiveDestroy set, END blocks meant for the supervisor only should check $$.

  • Works on Linux only, see Net::Tools::Socket::Pair.

SEE ALSO

Net::Tools::Socket::Pair, Net::Tools::Socket::Err, Data::Tools::Process::Forks

AUTHOR

Vladi Belperchinov-Shabanski "Cade"
      <cade@noxrun.com>
http://cade.noxrun.com/

COPYRIGHT AND LICENSE

Copyright (c) 2026 Vladi Belperchinov-Shabanski "Cade"

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.