How to run a user-supplied command in an infinite loop in a perl script, till user aborts it?
I need to run a command till the system I'm testing fails, or I abort the script. The command I need to run may开发者_运维技巧 vary, so I'm taking it as a command-line argument in quotes. But I can't seem to be able to run a command-line argument using the system command. Here's what I tried so far (edited my attempt with the script that @Cfreak provided, even with which I see the same issue):
#!/usr/bin/perl
while(1)
{
print "Iteration #: $count\n";
$retval = system ($ARGV[1]);
if( $retval != 0 ) {
print "System call $ARGV[1] failed with code $retval\n";
}
$count++;
}
If I do ./run ls
I see the following prints:
System call failed with code 65280
Iteration #: 1
System call failed with code 65280
Iteration #: 2
What am i doing wrong here ?
I believe that you want $ARGV[0] and not $ARGV[1]. You might also want to check to be sure that $ARGV[0] is present.
if( 0 > $#ARGV )
{
print "No command\n";
}
else
{
while(1)
{
print "$count\n";
my $ret = system( "ARGV[0]" );
if( 0 != $ret )
{
print "<$ARGV[0] failed with $ret\n";
exit;
}
$count++;
}
}
You have single quotes around your argument to system
. You don't need quotes at all (though double quotes would work)
Really you should also check the return value of the system call. It should return 0 if the call succeeds:
while(1)
{
print "Iteration #: $count\n";
$retval = system ($ARGV[1]);
if( $retval != 0 ) {
print "System call $ARGV[1] failed with code $retval\n";
}
$count++;
}
If you want to stop the script when the code fails then just use last
:
while(1)
{
print "Iteration #: $count\n";
$retval = system ($ARGV[1]);
if( $retval != 0 ) {
print "System call $ARGV[1] failed with code $retval\n";
last; # will break out of the loop
}
$count++;
}
65280 == 0xFF00, so the command did run (0xFF00 != -1), it did not die from a signal (0xFF00 & 0x7F == 0), and exited with exit code of 255 (0xFF00 >> 8 == 0xFF == 255).
So I guess you should start by checking what command you ran. Well, according to your own output, the empty string! Perhaps you want $ARGV[0]
instead of $ARGV[1]
?
Use use strict; use warnings;
!!! It would have avoided this entire problem.
精彩评论