An excellent question. I was brought up on UNIX machines
where you should always check the return code of any
program you run. As has already been stated a return value
of 0 indicates success, anything other value indicates something
went wrong.
On UNIX the value returned by system (and its colleagues)
is signal_number+256*exit_value. This means that when we
call an external program we should inspect the return and interpret the
error if there was one. I have a routine to do that (below).
I tested this out on Windows (running 5.005!) and it works the same there.
In my programs I have a special version of system so when I want
to run an external program I do:
&do_system("perl exit1.pl");
and I don't have to keep remembering to say:
system("perl exit1.pl") || die "Failed to run exit1.pl\n";
Anyway here is my old function for your edification…
# This is Perl4 code, I leave the translation to Perl5
# to the reader
sub do_system
{
local($cmd, $reportpattern) = @_;
local($ret);
print "# Do command $cmd\n" if($verbose);
$ret = system($cmd);
&interp_ret($cmd, $?, $reportpattern);
return($ret);
}
sub interp_ret
{
local($cmd,$ret,$reportpattern) = @_;
local($sig,$val,%sig_names,$sig_name);
return if(!$ret);
$sig = ($? & 0xff);
$val = $? >> 8;
return if ($reportpattern && ! eval($reportpattern));
# Not quite portable but gets close enough
%sig_names =
(1 ,"SIGHUP" ,2 ,"SIGINT" ,3 ,"SIGQUIT" ,4 ,"SIGILL" ,5 ,"SIG
+TRAP" ,
6 ,"SIGIOT" ,7 ,"SIGABRT",8 ,"SIGFPE" ,9 ,"SIGKILL" ,
10,"SIGBUS" ,11,"SIGSEGV" ,12,"SIGSYS",13,"SIGPIPE",14,"SIGA
+LRM",
15,"SIGTERM", 16,"SIGURG",17,"SIGSTOP",18,"SIGTSTP",19,"SIGC
+ONT",
20,"SIGCHLD",21,"SIGTTIN",22,"SIGTTOU",23,"SIGIO",24,"SIGXCP
+U",
25,"SIGXFSZ",26,"SIGVTALRM",27,"SIGPROF",28,"SIGWINCH",29,"S
+IGLOST",
30,"SIGUSR1",31,"SIGUSR2",);
print "\nIn script $0 the command \"$cmd\" seemed to fail\n";
$sig_name = $sig_names{$sig};
$sig_name = "Unknown SIG $sig" if(!$sig_name);
if($sig && $val)
{
print "Signal $sig_name caused return $val\n";
}
elsif($sig)
{
print "Signal $sig_name\n";
}
else
{
print " Returned status $val\n";
}
}
|