Using Perl, how do I check if a process with given name is running or not?

perl, process, windows

Solution

Take a look at the following example that uses the Win32::OLE module. It lets you search for running processes whose names match a given regular expression.

#! 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/^/;

Problem

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. So how to know if a process with particular name is running or not? Is there any Perl module which provides this feature?

Original source