in reply to why divide 256 for the exit code

...because the lower 8 bits of the exit code might contain information of interest, too (like the signal number that made the process die, and whether it core dumped — see system).  If Perl returned the high 8 bits only (by dividing the exit code by 256 itself prior to returning it), that info would not be available.

Replies are listed 'Best First'.
Re^2: why divide 256 for the exit code
by zhujian0805 (Sexton) on Sep 07, 2009 at 14:28 UTC
    thanks monk, for example, if i write a C program as below: main() { exit(100); } then, i invoke it from perl, and print the exit code, it's 25600. it convert to binary is: 1100100 00000000. so the high 8 bits is: 1100100(100), and the low 8 bits is: 00000000. if this C programm ran abnormally, the low 8 bits may contain info of interest, so use $? & 127 OR $? & 128. am'i right?
      You want 8 bits, not 7. IMHO, if you are doing bit operations, you should use hex (or octal if you are old-school) representations, so that it is clear. In this case, you should & with 0xff
        In this case, you should & with 0xff

        Actually, I think it's sufficient to use $? & 0x7f (or $? & 127 in decimal) to test for abnormal termination.  That's what the code snippet in system suggests. Also, the system header files responsible for the exit status handling (e.g. /usr/include/bits/waitstatus.h in my case) usually define those macros (among others):

        #define __WTERMSIG(status) ((status) & 0x7f) /* Nonzero if STATUS indicates normal termination. */ #define __WIFEXITED(status) (__WTERMSIG(status) == 0)

        (from that I would conclude that the core-dumped bit ($? & 128) doesn't occur in isolation (i.e. without WTERMSIG being non-zero) )