I tend to use the system() function pretty often, and I want to make sure I detect any problems. So, I think this means I want to make sure that programs I run always have an exit status of 0.

My understanding of the system function is that it returns a 16-bit value, where the high 8 bits are the exit status, and the low 8 are the signal id. Is that correct?

It also seems that I don't actually have to save the exit status after every use of system(), since the value also gets stored in $?.

I don't expect the programs I'm running to be killed by any signals (unless I'm the one doing the sending) ... So, I think this means I'm only concerned that the high 8 bits are all off. Therefore, does this mean I should be carefully making my system calls like this:

system('some_shell_command') >> 8 and die "Failed!"; # or else (same thing), system('some_program'); if ($? >> 8 != 0) { die "Failed!"; }

or would the following suffice? :

system('foobar') == 0 or die "Failed!"; # or equivalently system('foobar'); if ($? != 0) { die "Failed!"; }

Also, I notice in the docs for system(), there's this:

if ($? == -1) { print "failed to execute: $!\n"; } elsif ($? & 127) { printf "child died with signal %d, %s coredump\n", ($? & 127), ($? & 128) ? 'with' : 'without'; } else { printf "child exited with value %d\n", $? >> 8; }

For the if expression, if the exit status is 16 bits, then the value goes from 0 to 655535. What does it mean to check if it's -1?

For the elsif expression, why are they bitwise anding it with 127? 127 in binary is 0b0111_1111. So, that's only giving me the bottom 7 bits of $?, not 8. Why throw away that top bit in the bottom byte?


In reply to return value from system call, exit status, shift right 8, bitwise and, $? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.