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目录?
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
#!/usr/bin/perl -w
use strict;
use warnings;
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;
}
复制代码
./process_grep.pl core
复制代码
回复
1#
kingfighters
作者:
sjdy521
时间:
2014-05-04 17:41
本帖最后由 sjdy521 于 2014-05-04 17:43 编辑
回复
4#
kingfighters
自己写来写去不如用现成的模块,相当于自己写了个ps命令,这样真的有意思吗。。
Proc::ProcessTable
复制代码
# A cheap and sleazy version of ps
use Proc::ProcessTable;
$FORMAT = "%-6s %-10s %-8s %-24s %s\n";
$t = new Proc::ProcessTable;
printf($FORMAT, "PID", "TTY", "STAT", "START", "COMMAND");
foreach $p ( @{$t->table} ){
printf($FORMAT,
$p->pid,
$p->ttydev,
$p->state,
scalar(localtime($p->start)),
$p->cmndline);
}
# Dump all the information in the current process table
use Proc::ProcessTable;
$t = new Proc::ProcessTable;
foreach $p (@{$t->table}) {
print "--------------------------------\n";
foreach $f ($t->fields){
print $f, ": ", $p->{$f}, "\n";
}
}
复制代码
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2