windows 使用 Perl,如何检查具有给定名称的进程是否正在运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1023781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Perl, how do I check if a process with given name is running or not?
提问by Canopus
Using Perl, how do I check if a particular Windows process is running or not? Basically, I want to start a process using 'exec', but I should do this only if it is not already running.
使用 Perl,如何检查特定的 Windows 进程是否正在运行?基本上,我想使用“exec”启动一个进程,但只有在它尚未运行时才应该这样做。
So how to know if a process with particular name is running or not? Is there any Perl module which provides this feature?
那么如何知道具有特定名称的进程是否正在运行?是否有提供此功能的 Perl 模块?
回答by Greg Bacon
Take a look at the following example that uses the Win32::OLEmodule. It lets you search for running processes whose names match a given regular expression.
请看以下使用Win32::OLE模块的示例。它允许您搜索名称与给定正则表达式匹配的正在运行的进程。
#! perl
use warnings;
use strict;
use Win32::OLE qw(in);
sub matching_processes {
my($pattern) = @_;
my $objWMI = Win32::OLE->GetObject('winmgmts://./root/cimv2');
my $procs = $objWMI->InstancesOf('Win32_Process');
my @hits;
foreach my $p (in $procs) {
push @hits => [ $p->Name, $p->ProcessID ]
if $p->Name =~ /$pattern/;
}
wantarray ? @hits : \@hits;
}
print $_->[0], "\n" for matching_processes qr/^/;
回答by Jeremy Smyth
You're probably looking for Proc::ProcessTable(assuming you're using Unix!). It gives you access to the list of processes, and you can query its fields to find the process with the name. There are related packages to allow you to get at individual processes, depending what you want to do.
您可能正在寻找Proc::ProcessTable(假设您使用的是 Unix!)。它使您可以访问进程列表,您可以查询其字段以查找具有该名称的进程。有相关的软件包可让您了解各个流程,具体取决于您想要做什么。
回答by ysth
Maybe you don't have control over the second process, but if you do, a good way to do this is to have the process write its pid ($$
) out to a file in a known location. Then you can read the file and see if that pid exists using kill($pid, 0)
.
也许您无法控制第二个进程,但如果您控制了,一个好方法是让该进程将其 pid ( $$
)写入已知位置的文件中。然后您可以读取该文件并查看该 pid 是否存在使用kill($pid, 0)
.
回答by Anon
What you really want is a way to stop a process from running if it is already running (what if you have two different programs with the same name, or decide to name your program explorer.exe?) This works for me on Linux:
您真正想要的是一种阻止进程运行的方法,如果它已经在运行(如果您有两个同名的不同程序,或者决定将您的程序命名为 explorer.exe 怎么办?)这在 Linux 上对我有用:
use Fcntl ':flock';
open SELF, '<', ##代码## or die 'I am already running...';
flock SELF, LOCK_EX | LOCK_NB or exit;
In my testing that code does not want to be in any block.
在我的测试中,该代码不希望位于任何块中。
(source)
(来源)