johnnywang has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have a bunch of long running perl processes, each started from its own DOS window:
1st DOS window: perl foo.pl a 2nd DOS window: perl foo.pl b etc.
Now I'd like to write a another perl script that will kill a particular process depending on some other logic. I guess I have two questions: how to find the particular process (e.g., the process that was started as "perl foo.pl a"?), and how to kill it. Thanks.

Replies are listed 'Best First'.
Re: How to kill a windows process by command name?
by ickyb0d (Monk) on Nov 18, 2005 at 18:55 UTC

    might want to check out this recent node on how to find a process name (under windows).

    Also you might want to check out what CPAN has to offer. Win32API::Process looks pretty promising. hope this gets you started.

Re: How to kill a windows process by command name?
by johnnywang (Priest) on Nov 18, 2005 at 20:10 UTC
    Thanks to everyone, I figured this out, here's the code:
    use strict; use Win32::Process::Info; use Win32::Process; Win32::Process::Info->Set(variant=>'WMI'); my $pi = Win32::Process::Info->new(); for($pi->ListPids){ my ($info) = $pi->GetProcInfo($_); if($info->{CommandLine} eq 'perl foo.pl a'){ my $obj; my $pid = $info->{ProcessId}; Win32::Process::Open($obj,$pid,1); $obj->Kill(0); print "Killed $pid\n\n"; } }

      You could replace the use of Win32::Process with a call to perl's built-in kill using a signal value of 2 (or 21 or -9 work, as do many others).

      use strict; use Win32::Process::Info; Win32::Process::Info->Set(variant=>'WMI'); my $pi = Win32::Process::Info->new(); for($pi->ListPids){ my ($info) = $pi->GetProcInfo($_); if($info->{CommandLine} eq 'perl foo.pl a'){ my $obj; my $pid = $info->{ProcessId}; kill 2, $pid; print "Killed $pid\n\n"; } }

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
Re: How to kill a windows process by command name?
by gasho (Beadle) on Nov 18, 2005 at 19:08 UTC
    @A=`ps -o pid,comm=CMD`; @B=`ps -o pid,comm=CMD -u SYSTEM`; push(@B,@A); @C=grep(/BIBusTKServerMa.*|cogbootstrap.*|java.*|EXCEL.*|DevConsole.*| +cogconfigw.*/,@B); foreach $e(@C){ $z=substr($e,0,5); push(@AllPIDtobeKilled ,$z); } foreach $PID(@AllPIDtobeKilled){ system("kill -9 $PID"); #print "$PID\n"; }