Valid return code from system()

In the past when programming in Perl, and used the system() call or function to run something on the local OS, I would use something like this:

$rc = system($command);
if ($rc){ print "$command returned $rc\n";}

Recently, I was reviewing someone else’s code and noticed that they did the same thing this way:

system($command);
if (($? >> 8) != 0) { print STDERR "$command exited with code $?, aborting\n";}

I was curious why they were using a bitwise shift right to the system’s return code. After some research, I found that this is the proper way to find the actual response from the command you ran. The reason for this is that the system call relies on the operating system’s wait() call. The wait call returns 16 bits (two bytes), the bottom 8 bits (or low byte) contains system information (kill signals, program dumps, etc.) and the top 8 bits (or high byte) contains the actual exit value of the command. So by shifting the result 8 positions, the extra low byte information is removed and you are left with the important value about success or failure of the external command.

This should be uniform across all operating systems, but here is the important sections from the man page for the wait call on a Solaris 9 machine:

o If the child process stopped, the high order 8 bits of status will contain the number of the signal that caused the process to stop and the low order 8 bits will be set equal to WSTOPFLG.

o If the child process terminated due to an _exit() call, the low order 8 bits of status will be 0 and the high order 8 bits will contain the low order 8 bits of the argument that the child process passed to _exit(); see exit(2).

o If the child process terminated due to a signal, the high order 8 bits of status will be 0 and the low order 8 bits will contain the number of the signal that caused the termination. In addition, if WCOREFLG is set, a “core image” will have been produced; see signal(3HEAD) and wstat(3XFN).





Please VOTE for this page at: ADD TO DEL.ICIO.US | ADD TO DIGG | ADD TO FURL | ADD TO NEWSVINE | ADD TO NETSCAPE | ADD TO REDDIT | ADD TO STUMBLEUPON | ADD TO TECHNORATI FAVORITES | ADD TO SQUIDOO | ADD TO WINDOWS LIVE | ADD TO YAHOO MYWEB | ADD TO ASK | ADD TO GOOGLE


Leave a reply