use strict; use warnings; use English qw( -no_match_vars ); use POSIX qw( :sys_wait_h ); # Fork 5 child processes my $num_processes = 5; for (my $i = 0; $i < $num_processes; $i++) { my $pid = fork(); if ($pid == 0) { # Child process doWork(); exit; } elsif (!defined $pid) { die "Failed to fork: $OS_ERROR"; } } # Handle SIGCHILD and restart any child processes that have exited $SIG{CHLD} = sub { while ((my $pid = waitpid(-1, WNOHANG())) > 0) { my $exit_code = $CHILD_ERROR >> 8; if ($exit_code == 0) { print "Child process $pid exited successfully\n"; } else { print "Child process $pid exited with code $exit_code, restarting\n"; my $new_pid = fork(); if ($new_pid == 0) { # Child process doWork(); exit; } elsif (!defined $new_pid) { die "Failed to fork: $OS_ERROR"; } } } }; # Main process waits for child processes to exit while (1) { sleep(1); } # Function for child processes to do work sub doWork { # Your code here print "Child process $$ doing some work\n"; sleep(10); }