我刚写了一个perl脚本,它正在重启linux服务器上的服务列表。它的目的是作为一个cron工作。当我执行脚本时,我不断收到此错误;
root@www:~/scripts# ./ws_restart.pl
* Stopping web server apache2 [ OK ]
sh: Syntax error: "(" unexpected
* Stopping MySQL database server mysqld [ OK ]
sh: Syntax error: "(" unexpected
用于执行此操作的调用是;
system("/etc/init.d/apache2 stop");
system("/etc/init.d/mysql stop");
如果需要,我可以粘贴整个脚本代码,但我认为这是问题的根源,只需要知道如何阻止它。
有什么想法吗?
这是整个脚本;
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $old_pids = {};
my $post_stop_ids = {};
my @services = qw/apache2 mysql solr/;
my $app_dir = '/home/grip/apps/eventfinder';
# collect existing pids then kill services
foreach my $service (@services) {
# gather up existing pids
$old_pids->{$service} = [ get_pids_by_process($service) ];
# issue stop command to each service
set_service_state($service, 'stop');
# attempt to regather same ids
$post_stop_ids->{$service} = [ get_pids_by_process($service) ];
# kill any rogue ids left over
kill_rogue_procs($post_stop_ids->{$service});
# give each kill time to finish
sleep(5);
}
# attempt to restart killed services
foreach my $service (@services) {
# issue start command to each service
set_service_state($service, 'start');
# Let's give each service enough time to crawl outta bed.
# I know how much I hate waking up
sleep(5);
}
# wait for it!...wait for it! :P
# Pad an extra 5 seconds to give solr enough time to come up before we reindex
sleep(5);
# start the reindexing process of solr
system("cd $app_dir ; RAILS_ENV=production rake reindex_active");
# call it a day...phew!
exit 0;
sub kill_rogue_procs {
my @ids = shift;
# check if we still have any rogue processes that failed to die
# if so, kill them now.
if(scalar @ids) {
foreach my $pid (@ids) {
system("kill $pid");
}
}
}
sub set_service_state {
my ($proc, $state) = @_;
if($proc eq 'apache2') {
system("/etc/init.d/apache2 $state");
} elsif($proc eq 'mysql') {
system("/etc/init.d/mysql $state");
} elsif($proc eq 'solr') {
system("cd $app_dir ; RAILS_ENV=production rake sunspot:solr:$state");
}
}
sub get_pids_by_process {
my $proc = shift;
my @proc_ids = ();
open(PSAE, "/bin/ps -ae | grep $proc |") || die("Couldn't run command");
while(<PSAE>) {
push @proc_ids, $_ =~ /(\d{1,5})/;
}
close PSAE;
return @proc_ids;
}
答案 0 :(得分:3)
实际上,我对kill_rogue_procs中@ids中的内容更加怀疑。这是ps后跟grep的结果,如果ps没有返回任何结果或者pid不是5位数,可能会出现伪造值。
答案 1 :(得分:3)
这是错误的:
sub kill_rogue_procs {
my @ids = shift;
# check if we still have any rogue processes that failed to die
# if so, kill them now.
if(scalar @ids) {
从您传递给此子的内容,@ids将始终包含单个数组引用,因此(标量@ids)将始终为true。这也意味着你最终会将以下内容传递给sh
:
kill ARRAY(0x91b0768)
你想要类似的东西(如果arrayref为空,无论如何都没有任何东西可以循环):
my $ids = shift;
...
for my $pid (@$ids) {
kill SIGTERM => $pid;
或者代替循环:
kill SIGTERM => @$ids;
此外,无需将系统调用到kill进程。
对此,我添加了最后一行,所以你不要grep grep进程本身:
sub get_pids_by_process {
my $proc = shift;
$proc =~ s/^(.)/[$1]/;
答案 2 :(得分:1)
由于sh
正在引发错误,我非常确定system
的一个参数正在扩展到意外情况。我会在将所有参数传递给系统之前将其打印出来进行快速调试。