- Perl ›
- Predefined variable ›
- here
Exit status of child process $?
Use the predefined variable "$?" To get the exit status of the child process.
If wait waits for the child process to terminate, $? Contains multiple values, including the exit status of the child process. $? Is also set when a child process is executed using system function.
The method of interpreting $? Is a little complicated. $? Is set to a 16-bit value. The exit status of the child process is set to the upper 8 bits . The 8th bit of the lower 8 bits indicates whether a core dump was generated . The lower 8 bits up to the 7th bit represent the signal number that terminated the process , if any.
| - -- -- -- -- -- -- --- + - -- + - -- -- -- -- -- - | | 8 | 1 | 7 | | - -- -- -- -- -- -- --- + - -- + - -- -- -- -- -- - | | | | Exit Status Signal that terminated the child process of the core dump occurrence
So you need to shift $? To the right by 8 bits to get the exit status.
# Get exit status my $exit_value = $? >> 8;
To see if a core dump has occurred
# Whether a core dump has occurred my $dumped_core = $? & 128;
will do. Since 128 is 10000000 when converted to a binary number, the bit product is 0 except for the 8th bit. To see the signal number that killed the child process
# Signal number that terminated the child process my $signal_num = $? & 127;
will do. Since 127 is a binary number and is 01111111, the lower 7 bits can be obtained by taking the bit product.
Check if the child process has terminated
The wait function returns control when a CHLD signal occurs. This means that control returns not only when the child process terminates, but also when the child process is stopped or restarted.
Use the WIFEXITED function to see if the child process has terminated.
use POSIX q (:sys_wait_h); my $is_finished = WIFEXITED ($?);
Example to see the exit status of the child process
The exit status is 255 because we called die in the child process. You can see that the parent process is getting this status.
use strict; use warnings; use POSIX qw(:sys_wait_h); 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\n"; my $exit_value = $? >> 8; my $dumped_core = $? & 128; my $signal_num = $? & 127; my $is_finished = WIFEXITED ($?); print "Exit code of child process: $exit_value\n"; print "whether a core dump has occurred: $dumped_core\n"; print "Signal that terminated the child process: $signal_num\n"; print "whether the child process has terminated: $is_finished\n"; } else { # Wait 2 seconds in child process sleep 2; print "child process\n"; die; }
The execution result is
Child process Died at c.pl line 29. Parent process (child process ID: 13830) Exit code of child process: 255 Whether a core dump has occurred: 0 Signal that terminated the child process: 0 Whether the child process has terminated: 1
It looks like.