【发布时间】:2015-08-01 01:27:17
【问题描述】:
我有一些这样的 perl 代码来获取进程的 pid,如果它 存在。我想知道 pgrep 的返回状态,以便确定 pid 是否有效。代码如下:
#!/usr/bin/perl -w
my $pid=`pgrep -n -f \"akonadiserver\"`;
print "$? ";
chomp $pid;
print "Output1: $pid\n";
$pid=`pgrep -n -f \"akonadiserver\"`;
my $evalue=${^CHILD_ERROR_NATIVE};
chomp $pid;
print "Output2: $pid, $evalue\n";
但是每当我运行它时,我都会得到以下信息:
0 Output1: 3054
Output2: 3056, 0
再跑一次
0 Output1: 3059
Output2: 3061, 0
但在系统中:
$ pgrep -n -f akonadiserver
1862
这里看到的几个问题:
1) 返回的 pid 一直在变化,很可能是匹配的 grep 进程本身。
2) 我没有办法找出返回的 pid 是否有效。 $?
没用。
如何检查返回状态以及如何在 perl 中正确使用 pgrep?
【问题讨论】:
-
"find out of the pid returned is valid or not"是什么意思?来自documentation"pgrep looks through the currently running processes and lists the process IDs which match the selection criteria to stdout".. 所以任何返回的 PID 都将是一个正在运行的进程.. -
如上例所述,本应为 pid 的返回值不正确。我得到 3056、3059 等,而进程的实际 pid 是 1862。所以当它返回不同的(错误的)pid 时,我如何检查状态?因为显然 $?不工作。
-
您不能使用
pgrep的返回值来检查进程是否正确。返回值只是说明它是否找到任何进程。如果它找到一个、两个、三个或任何正数的进程,则返回值将为零。您需要做的是检查命令行中是否有某些东西(您认为是正确的进程)将其与不正确的进程分开,或者是否有其他一些特征(如开始时间)可以将正确的进程与其他进程分开..
标签: perl