Why is the exit code 255 instead of -1 in Perl?

后端 未结 3 1320
礼貌的吻别
礼貌的吻别 2020-12-03 22:21

Why is it that when I shift the exit code, $?, in Perl by eight, I get 255 when I expect it to be -1?

3条回答
  •  旧时难觅i
    2020-12-03 22:54

    Perl returns a subprocess exit code in the same manner as the C runtime library macro WEXITSTATUS, which has the following description in wait(2):

       WEXITSTATUS(status)
              evaluates to the least significant eight bits of the return code
              of the child which terminated, which may have been  set  as  the
              argument  to  a  call  to exit() or as the argument for a return
              statement in the main program.  This macro can only be evaluated
              if WIFEXITED returned non-zero.
    

    The important part here is the least significant eight bits. This is why you are getting an exit code of 255. The perlvar man page describes $? as follows:

       $?      The status returned by the last pipe close, backtick (‘‘) com-
               mand, successful call to wait() or waitpid(), or from the sys-
               tem() operator.  This is just the 16-bit status word returned
               by the wait() system call (or else is made up to look like it).
               Thus, the exit value of the subprocess is really ("$? >> 8"),
               and "$? & 127" gives which signal, if any, the process died
               from, and "$? & 128" reports whether there was a core dump.
    

    There is no special handling here for negative numbers in the exit code.

提交回复
热议问题