- Perl ›
- builtin functions ›
- here
wait function - waits for the termination of the child process
If you branch with fork, you don't know which of the parent and child processes will terminate first. This time, I will explain how the parent process waits for the child process to finish.
1. Wait for the end of the child process with wait
Use the wait function to wait for the child process to terminate. The wait function waits until one child process terminates . The return value is the process ID of the terminated child process . If the child process was automatically reclaimed for any reason, -1 will be returned.
my $pid = wait;
This is an example that waits for a child process. Let's modify the previous example a little. To make the result easier to understand, sleep function waits for 2 seconds before executing print statement on the child process side.
use strict; use warnings; my $pid = fork; die "Cannot fork:$!" unless defined $pid; if ($pid) { # Wait for the child process to finish. wait; print "parent process (child process ID: $pid)\n"; } else { # Wait 2 seconds in child process sleep 2; print "child process\n"; }
The output result is
Child process Parent process (child process ID: 25870)
It will be. You can see that the parent process is waiting for the child process.
2. Termination of child process and deletion from process table
When a child process terminates, it is not immediately deleted from the process table . (The process table is used by the OS to manage the process.)
Wait for the child process to be removed from the process table after it terminates. This condition is called the "dead child process." The child process waits for removal from the process table because the parent process needs to know the termination status of the child process .
Calling wait removes the terminated child process from the process table. The child process is also deleted from the process table when the parent process terminates.
3. Child process exit status
When you call wait
$?
Multiple data including the exit status of the child process are stored in the predefined variable called. Next time, I will explain how to get the exit status of the child process stored in $?.
4. What wait really does
In fact, wait is not waiting for the child process to terminate . Waiting for the child process to generate a CHLD signal . The CHLD signal occurs not only when the child process terminates, but also when the child process is stopped or restarted.
This means that using wait does not reliably recover dead child processes . To ensure that the dead child process is reclaimed, set the signal handler for the CHLD signal to IGNORE or use the waitpid function appropriately.