为什么“ps aux | grep x“比”pgrep x“给出更好的结果?
我刚刚在我的Ubuntu上尝试了以下命令,它没有显示任何东西:
pgrep php5
不应该返回php5的进程ID(以下命令只是这样做):
ps aux | grep php5
那么,这两个命令之间的区别是什么?
ps aux
包含完整的命令行(路径和参数),而pgrep只查看可执行文件名称的前15个字符
ps aux
返回每个进程的完整命令行,而pgrep
只查看可执行文件的名称。
这意味着grepping ps aux
输出将匹配路径中出现的任何内容或进程二进制的参数:例如`
-
ps aux | grep php5
ps aux | grep php5
将匹配/usr/share/php5/i-am-a-perl-script.pl
- 但是
pgrep php5
不会
从我的系统举一个例子 – 只有我们将使用python而不是php5
:
-
ps aux | grep python
ps aux | grep python
给了我们:
izx 2348 0.0 0.7 514928 15644? Sl Jun24 0:00 / usr / bin / python / usr / lib / unity-lens-video / unity-lens-video izx 2444 0.0 0.9 547392 18864? Sl Jun24 0:01 / usr / bin / python / usr / lib / unity-scope-video-remote / unity-scope-video-remote 根2805 0.0 0.5 95436 12204? S Jun24 0:00 / usr / bin / python / usr / lib / system-service / system-service-d izx 6272 0.0 2.9 664400 60320? SNl Jun24 1:16 / usr / bin / python / usr / bin / update-manager --no-focus-on-map root 11729 0.0 0.9 180508 19516? S Jun25 0:00 python / usr / lib / software-properties / software-properties-dbus
- 但是
pgrep python
只返回11729
,你可以从上面的列表中看到:
root 11729 0.0 0.9 180508 19516? S Jun25 0:00 python / usr / lib / software-properties / software-properties-dbus
ps aux | grep x
ps aux | grep x
命令比pgrep x
给出“更好”的结果,因为你缺少后者的选项。
只需使用pgrep
的-f
选项来搜索完整的命令行,而不仅仅是作为默认行为的进程名称,例如:
pgrep -f php5
与ps | grep
不同 你需要过滤掉grep
行或使用模式技巧的ps | grep
构造, pgrep
不会因为设计而自行选择。
此外,如果您的模式出现在ps
USER
列中,您将在输出中获得不需要的进程, pgrep
不会受此缺陷的影响。
如果您想要完整的详细信息而不仅仅是pids,您可以使用:
ps wup $(pgrep -f python)
这比更简单,更可靠
ps aux | grep python | grep -v grep
要么
ps aux | grep p[y]thon
diff <(ps aux|grep x) <(pgrep x) # :)