Active non-blocking waiting with waitpid

Up till now we were usig the wait function to wait for a child process to terminate. It is a blocking call that will wait till any of the child processes terminates.

There are other options as well. Using the waitpid function you could wait for a specific child to terminate using its PID or you can have a non-blocking way to check if there is any child-processes that has already terminated. The non-blocking wait mode allows the parent process to do other things while waiting for the child processes to do their job.

use strict;
use warnings;
use Time::HiRes qw(sleep);

use POSIX ':sys_wait_h';


sub main {
    my ($sleep, $exit) = @ARGV;

    die "Usage: $0 SLEEP EXIT\n" if not defined $exit;

    my $pid = fork();
    die 'Failed to fork' if not defined $pid;

    if ($pid == 0) {
        print "Child process PID $$\n";
        sleep $sleep;
        exit $exit;

    while (1) {
        my $pid = waitpid(-1, WNOHANG);
        if ($pid > 0) {
            my $exit_code = $?/256;
            print "Child process $pid finished with exit code $exit_code\n";
        print "Parent could do something else, but now sleeping\n";
        sleep 0.1;

perl 0 0
perl 1 0
perl 1 1