我编写了这个 Perl 脚本来自动化我的无线连接:
#!/usr/bin/perl
use strict;
my @modes = ("start", "stop");
my $mode = $modes[0];
my $kill_command = "sudo kill -TERM ";
sub check_args
{
if($#ARGV != 0)
{
print(STDERR "Wrong arguments\n");
print(STDERR "Usage: ./wicd.pl start|stop\n");
exit();
}
my @aux = grep(/^$ARGV[0]$/, @modes);
if (!@aux)
{
print(STDERR "Unknown argument\n");
print(STDERR "Usage: ./wicd.pl start|stop\n");
exit();
}
$mode = $ARGV[0];
}
check_args();
my @is_wicd_running = `ps -A | grep wicd`;
# START
if ($mode eq $modes[0])
{
if (!@is_wicd_running)
{
system("gksudo ifconfig wlan0 down");
system("sudo macchanger -r wlan0");
system("sudo wicd");
}
my @is_wicd_gui_running = grep(/wicd-client/, @is_wicd_running);
if (!@is_wicd_gui_running)
{
system("gksudo wicd-gtk &");
}
}
# STOP
else
{
for (@is_wicd_running)
{
my @aux = split(/ /, $_);
system("$kill_command$aux[1]");
}
system("sudo ifconfig wlan0 down");
}
问题是 macchanger 和 sudo ifconfig wlan0 down 没有执行(只有那些...)。奇怪的是,当通过 Perl 调试器 (perl -d) 调用脚本时,这些调用会执行。我认为这可能是一个时间问题,并在这些调用之前添加了一些 sleep() 调用,但没有改变。我也尝试过 system() 调用,也没有任何变化。
编辑:更奇怪的是,我发现如果我将脚本作为 perl wicd.pl 运行,它会正常运行,而 ./wicd.pl 则不会(它运行但存在上述问题)。我附上了整个脚本。 header 上使用的 Perl 解释器与 which perl 命令返回的相同。
有什么线索吗?提前致谢!
最佳答案
更多信息可能会有所帮助,同时确保\n 始终结束输出行。在
中尝试运行命令sub runx { foreach my $cmd ( @_ ) { my $out = qx("$cmd 2>&1"); my $x = $?; $out =~ s/\s*$/\n/s; printf "\%s (0x\%0x):\n\%s", $cmd, $x, $out; last if $x; } return $x; }
今天早上没时间运行这段代码,也不能删除我之前的评论。但是运行“which”命令的东西也可以确保你的命令在 PATH 上。
关于linux - Perl 脚本不执行某些外部调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7414249/