0

我正在执行以下操作:

#!/usr/bin/perl  
use strict;  
use warnings;  

my $proc = `ps -ef|grep -c myscriptname`;  
print $proc;  

当我在脚本中运行它时,它会打印 2。

ps -ef|grep -c myscriptname在命令行上只显示: 1
为什么?

同样的my $proc = qx/ps -ef|grep -c myscriptname/

更新
要清楚,我从somerandomscript.pl

更新 2
按照 edorqui 的建议,我删除-c了:

12013 15777 15776 0 14:11 pts/6 00:00:00 sh -c ps -ef | grep myscriptname   
12013 15779 15777 0 14:11 pts/6 00:00:00 grep myscriptname Argument "12013 15777 15776 0 14:11 pts/6 00:00:00 sh -c ps..." isn't numeric in numeric gt (>) at somerandomscript.pl line 8  

从脚本内部

4

4 回答 4

5

ps -ef命令显示 grep 本身。

要跳过此行为,请尝试查找与 grep 本身不匹配的正则表达式条件:

ps -ef | grep myscript[n]ame

或任何类似的东西可以做到:

ps -ef | grep myscriptnam[e]

解释

如果sleep在后台运行命令:

$ sleep 100 &
[1] 9768

然后寻找它ps -ef

$ ps -ef | grep sleep
me    9768  3673  0 14:00 pts/6    00:00:00 sleep 100
me    9771  3673  0 14:00 pts/6    00:00:00 grep --color=auto sleep

你得到两行:进程本身和grep寻找它的命令。为了避免它并只显示过程本身,我们可以:

$ ps -ef | grep -v grep | grep sleep

或在代码中使用正则表达式,使 grep 进程不匹配:

$ ps -ef | grep slee[p]
me    9768  3673  0 14:00 pts/6    00:00:00 sleep 100

因为线

me    9771  3673  0 14:00 pts/6    00:00:00 grep --color=auto sleep

中不匹配grep slee[p]

请参阅相关主题中的说明

于 2013-08-09T11:58:15.633 回答
1

我想你的 perl 脚本被命名为“myscriptname”。

当你运行这个脚本时,你有一个新进程(perl myscriptname.pl),它由 ps -ef 命令显示。另一个与 grep 命令有关(它有您要查找的文本)

于 2013-08-09T11:57:09.110 回答
1

@fedorqui 的回答是正确的——grep它匹配它自己在进程表中的调用,也许还有它的父 shell 的调用,尽管时间问题意味着这并不总是从 CLI 发生。

但是,另一种避免grep使用 perl 的方法是:

my $count = () = qx(ps -e -o cmd) =~ /myscriptname/mg;
# Now $count tells you the number of times myscriptname appears in the process table

请参阅此答案,了解为什么上面使用空括号。还要注意,您不需要完整 ps的输出 ( -f),您只需要匹配命令名称 ( -o cmd)。

于 2013-08-09T15:47:15.780 回答
0

看一下pgreppkill命令。这些是标准的 Linux 命令,比尝试执行 aps然后 grep 更容易使用。

此外,如果您确实使用ps,请查看-o选项。这些使您可以显示所需的列,并为您提供一种去除标题的方法。

于 2013-08-09T14:05:08.857 回答