欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

perl查找进程PID的例子

程序员文章站 2022-07-11 15:15:11
主要是利用查找/proc目录下的相关文件进行查找. #!/usr/bin/perl use strict; use warnings; #usage: p...

主要是利用查找/proc目录下的相关文件进行查找.

#!/usr/bin/perl 
use strict;
use warnings;
#usage: process_grep.pl  processname
exit( main(@argv) );
 
sub main {
  my $phash;
  my $processname = shift;
  my $proc_dir  = "/proc";
  chdir $proc_dir;
  my @pids = glob "[0-9]*";
  for my $pid (@pids) {
    open( fh, "$pid/cmdline" ) or die "can't $pid file $!";
    $phash->{$pid} = $_ while <fh>;
  }
  delete $phash->{"$$"};
  for my $pid ( keys %$phash ) {
    print $pid, "\n" if $phash->{$pid} =~ /$processname/;
  }
  return 0;
}