从Perl脚本中杀死一个进程 [英] Kill a process from perl script
问题描述
我试图按名称杀死进程,该进程将作为变量传递给系统命令.
I am trying to kill a process by name which i will pass as a variable to a system command.
以下是我所拥有的:
my $processName=$ARGV[0];
print "$processName\n";
system(q/kill -9 `ps -ef | grep '$processName' | grep -v grep | awk '{print $2}'`/);
上面的脚本抛出错误:
kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
但是,如果我直接在系统命令中输入进程名称,它将起作用.
However, if i directly enter the process name inside the system command, it works.
有人可以帮我吗?
推荐答案
一个问题是,调用脚本的命令行具有您要查询的进程的名称,这是设计使然;所以发现的一件事就是脚本本身.
One problem is that the command line that invokes the script has the name of the process which you then query, by design; so one thing found will be the script itself.
这可以防止,但是为什么要通过这么大的管道进入系统?
This can be guarded against, but why go out to the system with that big pipeline?
例如使用 Proc ::在Perl中查询进程: ProcessTable
use warnings;
use strict;
use Proc::ProcessTable;
my $proc_name = shift // die "Usage: $0 process-name\n"; #/
my $pid;
my $pt = Proc::ProcessTable->new();
foreach my $proc (@{$pt->table}) {
next if $proc->cmndline =~ /$0.*$proc_name/; # not this script
if ($proc->cmndline =~ /\Q$proc_name/) {
$pid = $proc->pid;
last;
}
}
die "Not found process with '$proc_name' in its name\n" if not defined $pid;
kill 9, $pid; # must it be 9 (SIGKILL)?
my $gone_pid = waitpid $pid, 0; # then check that it's gone
请注意,通过发送SIGTERM
(通常为15)而不是SIGKILL
来杀死"一个进程要好得多.
Note that it is far nicer to "kill" a process by sending it SIGTERM
(usually 15), not SIGKILL
.
寻找进程名称"可能很危险,因为在现代系统上运行的许多进程包含长命令行,其中可能包含该单词.该代码使用您的要求来简单地按提交的名称进行查询,但是我建议通过附加检查来加强这一点.
Looking for a process "name" can be perilous as there are many processes with long command lines running on a modern system that may contain that word. The code uses your requirement, to simply query by submitted name, but I recommend strengthening that with additional checks.
有关该模块可以查询的许多流程详细信息,请参见其存根模块.
For many process details that the module can query see its stub module.
即使您想自己解析进程表,我也只会得到ps -ef
,然后在脚本中对其进行解析.这样可以在确保您真正终止所需的内容时提供更大的灵活性.
Even if you'd rather parse the process table yourself I would get only ps -ef
and then parse it in the script. That gives far more flexibility in ensuring that you really terminate what you want.
这篇关于从Perl脚本中杀死一个进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!