通过命令行在 Linux 中查找进程数 [英] Finding process count in Linux via command line
问题描述
我一直在寻找在 Linux 中通过命令行查找同名正在运行的进程数量的最佳方法.例如,如果我想找到正在运行的 bash 进程的数量并获得5".目前我有一个脚本,它执行 'pidof ',然后对标记化的字符串进行计数.这工作正常,但我想知道是否有更好的方法可以完全通过命令行完成.在此先感谢您的帮助.
I was looking for the best way to find the number of running processes with the same name via the command line in Linux. For example if I wanted to find the number of bash processes running and get "5". Currently I have a script that does a 'pidof ' and then does a count on the tokenized string. This works fine but I was wondering if there was a better way that can be done entirely via the command line. Thanks in advance for your help.
推荐答案
在具有 pgrep
可用的系统上,-c
选项返回进程数的计数匹配给定的名字
On systems that have pgrep
available, the -c
option returns a count of the number of processes that match the given name
pgrep -c command_name
请注意,这是 grep
样式的匹配,而不是完全匹配,例如pgrep sh
也将匹配 bash
进程.如果您想要完全匹配,还可以使用 -x
选项.
Note that this is a grep
-style match, not an exact match, so e.g. pgrep sh
will also match bash
processes. If you want an exact match, also use the -x
option.
如果pgrep
不可用,你可以使用ps
和wc
.
If pgrep
is not available, you can use ps
and wc
.
ps -C command_name --no-headers | wc -l
ps
的 -C
选项将 command_name
作为参数,程序会打印一个关于可执行名称匹配的进程的信息表给定的命令名称.这是完全匹配,而不是 grep
样式.--no-headers
选项抑制表格的标题,通常打印为第一行.使用 --no-headers
,每个进程匹配一行.然后 wc -l
计算并打印其输入中的行数.
The -C
option to ps
takes command_name
as an argument, and the program prints a table of information about processes whose executable name matches the given command name. This is an exact match, not grep
-style. The --no-headers
option suppresses the headers of the table, which are normally printed as the first line. With --no-headers
, you get one line per process matched. Then wc -l
counts and prints the number of lines in its input.
这篇关于通过命令行在 Linux 中查找进程数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!