Chinaunix

标题: 怎么查询程序的process id [打印本页]

作者: kingfighters    时间: 2014-05-04 10:56
标题: 怎么查询程序的process id
有一个需求,现在是需要查询某个程序的pid,我实在不想再perl里面调用`pe -ef | grep core| grep -v grep`然后去再用awk取第二个字段,感觉这样好傻。。

不知道Perl里面是否有更好的实现方式?


作者: kingfighters    时间: 2014-05-04 11:09
core是需要查询的process名称,这些名称都是独有的
作者: sjdy521    时间: 2014-05-04 11:20
自己遍历/proc目录?
  1. http://bbs.chinaunix.net/thread-2199161-1-1.html
复制代码

作者: kingfighters    时间: 2014-05-04 12:43
回复 3# sjdy521

有趣,谢谢提醒,可以遍历这个目录中所有目录,找到目录中exe文件指向的符号链接,如果匹配的到,那么就是当前的运行的pid。。。

我试试看这样行不行。


   
作者: kingfighters    时间: 2014-05-04 14:32
http://blog.csdn.net/turkeyzhou/article/details/6704584

这个blog对于proc目录有一个更详细的描述
作者: mcshell    时间: 2014-05-04 17:09
  1. #!/usr/bin/perl -w
  2. use strict;
  3. use warnings;
  4. exit( main(@ARGV) );

  5. sub main {
  6.     my $Phash;
  7.     my $ProcessName = shift;
  8.     my $PROC_DIR    = "/proc";
  9.     chdir $PROC_DIR;
  10.     my @pids = glob "[0-9]*";
  11.     for my $pid (@pids) {
  12.         open( FH, "$pid/cmdline" ) or die "Can't $pid file $!";
  13.         $Phash->{$pid} = $_ while <FH>;
  14.     }
  15.     delete $Phash->{"$$"};
  16.     for my $pid ( keys %$Phash ) {
  17.         print $pid, "\n" if $Phash->{$pid} =~ /$ProcessName/;
  18.     }
  19.     return 0;
  20. }
复制代码
  1. ./process_grep.pl  core
复制代码
回复 1# kingfighters


   
作者: sjdy521    时间: 2014-05-04 17:41
本帖最后由 sjdy521 于 2014-05-04 17:43 编辑

回复 4# kingfighters


    自己写来写去不如用现成的模块,相当于自己写了个ps命令,这样真的有意思吗。。
  1. Proc::ProcessTable
复制代码
  1. # A cheap and sleazy version of ps
  2. use Proc::ProcessTable;

  3. $FORMAT = "%-6s %-10s %-8s %-24s %s\n";
  4. $t = new Proc::ProcessTable;
  5. printf($FORMAT, "PID", "TTY", "STAT", "START", "COMMAND");
  6. foreach $p ( @{$t->table} ){
  7.    printf($FORMAT,
  8.           $p->pid,
  9.           $p->ttydev,
  10.           $p->state,
  11.           scalar(localtime($p->start)),
  12.           $p->cmndline);
  13. }


  14. # Dump all the information in the current process table
  15. use Proc::ProcessTable;

  16. $t = new Proc::ProcessTable;

  17. foreach $p (@{$t->table}) {
  18.   print "--------------------------------\n";
  19.   foreach $f ($t->fields){
  20.     print $f, ":  ", $p->{$f}, "\n";
  21.   }
  22. }  
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2