Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

I would like to know how to check whether a system command has worked.
The system command attempts to mount a floppy on a Linux machine, and if it is successful, do some stuff.
The code I have used is as follows:

if (system "sudo /bin/mount /dev/fd0 /mnt/floppy") {# do some stuff} else {# display an error message}
The error message gets displayed the first time, but not the second time.
Should I be checking if the system call returns 0 rather than 1?

Thanks,

CJ

Replies are listed 'Best First'.
Re: checking on a system process
by bgreenlee (Friar) on Aug 19, 2004 at 10:29 UTC

    From perldoc -f system:

    The return value is the exit status of the program as returned by the "wait" call. To get the actual exit value shift right by eight (see below). See also "exec". [snip] You can check all the failure possibilities by inspecting $? like this: $exit_value = $? >> 8; $signal_num = $? & 127; $dumped_core = $? & 128; or more portably by using the W*() calls of the POSIX exten- sion; see perlport for more information.

    -b

Re: checking on a system process
by hanenkamp (Pilgrim) on Aug 19, 2004 at 11:42 UTC

    This isn't intended as an insult or anything, I just want you to get the best help in the most efficient way:

    This question is quite thoroughly answered in the documentation shipped with perl. I suggest you take a look at perldoc -f system (try man perlfunc on a Debian system without perldoc) for starters. This documentation is also available online at system.

    Usually, the first place to look for info is perltoc which is a huge table of contents for things in the perl documentation. This has links to the perl FAQs, which are a fairly helpful resource as well.

Re: checking on a system process
by Random_Walk (Prior) on Aug 19, 2004 at 10:25 UTC
    You could try something like this

    my $result=`sudo /bin/mount /dev/fd0 /mnt/floppy`; if ($?) { # there was an non zero return code print "There was an error: $?\n"; print $result } else { # looks like it worked }

    With system you get the exit code of the forked child returned, perldoc suggests the following to handle errors.

    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; }
    Cheers,
    Random.