NAME

Proc::Fork::Control - management front end to fork()

DESCRIPTION

Proc::Fork::Control manages fork() for you. It caps how many children a process may run, tracks those children, and can either block until they exit or return as soon as they have been started.

The interface is a set of exported functions. Forking copies the interpreter, so the module keeps its state in a process-global heap instead of in an object.

SYNOPSIS

use strict;
use warnings;
use Proc::Fork::Control;
use Fcntl qw(:flock);

# Allow 25 concurrent children of this process.
cfork_init(25);

# Nonblocking mode is what makes the cap queue workers. In the
# default blocking mode, cfork() waits for the child before it
# returns, so only one child exists at a time.
cfork_nonblocking(1);

for my $i (1 .. 50) {
	cfork(sub {
		cfork_init(2);
		cfork_nonblocking(1);

		for my $letter ('A' .. 'Z') {
			cfork(sub {
				flock(STDOUT, LOCK_EX);
				print STDOUT "Fork: $i: $letter\n";
				flock(STDOUT, LOCK_UN);
				cfork_exit(0);
			});
		}

		cfork_nonblocking(0);
		cfork_wait();
		cfork_exit(0);
	});
}

cfork_nonblocking(0);
cfork_wait();

REQUIREMENTS

Perl 5.8 or newer, POSIX, and Time::HiRes. Time::HiRes has been required since version 1.3.

LIMITATIONS

The module installs its own $SIG{CHLD} handler in each process that calls cfork_init() and is not itself a forked child. A handler you installed earlier is replaced.

State is one heap per process. There is no object, and the module is not a thread-safe work queue.

cfork_daemonize changes the working directory to /.

METHODS

cfork(CODE, ...)

Fork once, when this process is under its child cap.

Each CODE reference runs in the child, in order. If the child returns from the last reference without calling cfork_exit, it exits with status 2. A reference that throws aborts the child with that error, and later references do not run.

While the cap is full, cfork waits for a slot. In the default blocking mode it then waits for every child of this process, including the one it just started, before it returns the child pid. Turn on cfork_nonblocking when the parent must keep more than one child at a time. In that mode cfork returns the pid as soon as the child has been created.

The child starts with an empty child list and must call cfork_init itself before it calls cfork. It does not inherit the parent's pids.

On success the parent receives the child pid. On failure cfork returns undef and sets cfork_errstr. A failed fork is reported this way and does not run the child code in the parent.

cfork_nonblocking(BOOL)

Turn nonblocking mode on when BOOL is true, and off when it is false or omitted.

In nonblocking mode cfork, cfork_wait, and cfork_wait_pid return without waiting for children to exit. The child cap still applies: cfork waits for a free slot before it forks.

Call cfork_nonblocking(0) again when that stretch of work is finished, then cfork_wait(). The call returns the new mode, 1 or 0.

Example

cfork_nonblocking(1);

cfork(sub {
	# parent returns while this child is still running
	cfork_exit(0);
});

cfork_nonblocking(0);
cfork_wait();

cfork_is_child()

Return 1 when this process was started by cfork, otherwise 0.

cfork_has_children()

Return 1 when this process still has children started by cfork, otherwise 0.

Children that have already been reaped do not count. In blocking mode cfork itself reaps before it returns, so call this from the parent while nonblocking mode is on.

cfork_errstr()

Return the last error string set by cfork, or undef if none has been set. A later success does not clear it.

cfork_init(CHILDREN)

Install the SIGCHLD reaper and set the maximum number of live children of this process to CHILDREN. Call it before any cfork.

A later call in the parent, while children are still running, keeps those children and adds CHILDREN to the current maximum. A value of 0 does not change the maximum in that case. When no children are running, the call replaces this process's heap and stores CHILDREN as the maximum, including zero. cfork then fails until a positive maximum is set.

Returns 1.

The second argument is internal. cfork uses it so a new child drops the pid list it inherited.

cfork_exit(STATUS)

Store STATUS and exit the current process with it. An omitted status exits 0. This does not return.

The stored status stays in the process that called cfork_exit. The parent observes it as the child's exit status after cfork_wait, not through cfork_exit_code.

cfork_exit_code()

Return the status last passed to cfork_exit in this process, or undef if this process has not called it.

cfork_maxchildren(COUNT)

Set the maximum number of children to COUNT when an argument is given, including zero. With no argument, leave the maximum alone. Returns the current maximum, or undef if cfork_init has not set one.

cfork_wait(SECONDS)

Block until every child started by cfork has exited.

SECONDS, when it is a positive number, is a timeout. The call then returns false if any child is still running when the timeout expires, and 1 if every child has exited. A missing or invalid timeout waits without a deadline. The timeout is measured with Time::HiRes, so a fraction of a second is honored.

In nonblocking mode the call returns 1 immediately and does not reap.

cfork_wait_pid(PID, ...)

Wait until every given pid has exited. Pids do not have to be children started by this module. A pid that is not a positive integer is ignored.

In nonblocking mode the call returns 1 immediately.

Returns 1. Dead processes are reaped while the call waits, so a zombie child does not keep the loop running.

cfork_active_children()

Return the number of children started by cfork that are still running. Reaps exited children first.

cfork_daemonize(BOOL)

Detach the calling process.

The call changes directory to / and forks. The process that called cfork_daemonize then exits with status 4. The child becomes a new session leader and returns 1.

When BOOL is false or omitted, standard input, output, and error are reopened on /dev/null before the fork. A true value leaves them attached to whatever they are attached to now.

Failures die. This is the behavior the function has had since 1.2.

cfork_sleep(SECONDS)

Sleep for SECONDS whole seconds. If a signal interrupts the sleep early, the call keeps sleeping for the rest of the interval.

Returns the number of seconds slept, which is SECONDS when the call finishes the interval. Returns 0 when SECONDS is 0. Returns undef when SECONDS is not a non-negative integer.

cfork_usleep(MICROSECONDS)

Sleep for MICROSECONDS. Interrupted sleeps are resumed until the requested interval has elapsed, the same way as cfork_sleep.

Returns the number of microseconds slept. Returns 0 when the argument is 0. Returns undef when the argument is not a non-negative integer.

cfork_ssleep(SECONDS)

Sleep for SECONDS whole seconds using select, for environments where sleep returns early or not at all. A signal that wakes select does not end the wait; the call loops until the interval has passed.

Returns SECONDS, or 0 when the argument is 0. Returns undef when the argument is not a non-negative integer.

cfork_kill_children(SIGNAL)

Send SIGNAL to every child still tracked by this process. The signal defaults to TERM.

Returns the number of processes signaled, or 0 when there are none.

cfork_list_children(AS_HASH)

Return the pids of children that are still running.

When AS_HASH is true, return those pids paired with the epoch second each child was started, as a list suitable for assignment to a hash.

cfork_child_dob(PID)

Return the epoch second at which this process started PID with cfork.

Return undef when PID is not a child still tracked here. Reaped children are forgotten.

AUTHOR

Colin Faber, cfaber@fpsn.net

COPYRIGHT AND LICENSE

Copyright (C) 2014-2026 Colin Faber

The source of this module is released under the GNU General Public License, version 2. The license text is in LICENSE.GPL. This distribution also includes the Artistic License 1.0 in LICENSE, as it has since the first public release.

SUPPORT

Please report bugs at https://github.com/cfaber/Proc-Fork-Control/issues.