Why is Perl's $? returning the wrong value for the exit code of a forked process?

前端 未结 2 1941
小鲜肉
小鲜肉 2021-01-05 17:22

Consider this trivial example of fork()ing then waiting for a child to die in Perl:

#!/usr/bin/perl

use strict;
use warnings;

if (fork() == 0) {
        ex         


        
相关标签:
2条回答
  • 2021-01-05 17:42

    The child might not even have gotten to call exit. As such, $? packs more information than just the exit parameter.

    if    ( $? == -1  ) { die "Can't launch child: $!\n"; }
    elsif ( $? & 0x7F ) { die "Child killed by signal ".( $? & 0x7F )."\n"; }
    elsif ( $? >> 8   ) { die "Child exited with error ".( $? >> 8 )."\n"; }
    else                { print "Child executed successfully\n"; }
    

    This is documented more clearly in system's documentation.

    0 讨论(0)
  • 2021-01-05 17:48

    It's documented in the $? section of the perlvar man page.

    i.e. the real exit code is $? >> 8.

    0 讨论(0)
提交回复
热议问题