perl function waitpid

w‮.ww‬theitroad.com

The waitpid function in Perl waits for a child process to exit or stop and returns its process ID. Here's the syntax:

waitpid($pid, $flags);

where $pid is the process ID of the child process to wait for, and $flags is an optional integer that can modify the behavior of the function.

Here's an example that demonstrates the usage of waitpid function:

use strict;
use warnings;

my $pid = fork();
if (!defined $pid) {
    die "Failed to fork: $!";
} elsif ($pid == 0) {
    print "Child process $$ is running\n";
    sleep 5;
    exit 42;
} else {
    print "Parent process $$ is waiting for child $pid to exit\n";
    my $kid = waitpid($pid, 0);
    if ($kid == $pid) {
        my $status = $? >> 8;
        print "Child process $kid exited with status $status\n";
    } else {
        die "waitpid failed: $!";
    }
}

In this example, we fork a child process and have it sleep for 5 seconds before exiting with status code 42. The parent process waits for the child process to exit using waitpid. Once the child process has exited, the parent process prints the process ID and exit status of the child process.