我有一个关于Linux进程ID的问题。如何获取同一组中的PID? 在Linux中,使用“ps”命令很容易获取所有PID或PGID,但是如何获取属于同一组的PID,换句话说,如何获取同一程序的PID? 请问有人能帮助我吗?谢谢!
我有一个关于Linux进程ID的问题。如何获取同一组中的PID? 在Linux中,使用“ps”命令很容易获取所有PID或PGID,但是如何获取属于同一组的PID,换句话说,如何获取同一程序的PID? 请问有人能帮助我吗?谢谢!
from man ps
To print a process tree:
ps -ejH
ps axjf
pstree
还可以帮助查看进程树。
更新:使用 pidof
来查找指定程序的进程 PID。例如,pidof chrome
将获取所有 Chrome 的 PID。
所有其他答案似乎都提到了ps
,但没有一个尝试直接访问/proc
。
在"Unix&Linux"上有另一种方法:
awk '{print $5}' < /proc/$pid/stat
perl -l -0777 -ne '@f = /\(.*\)|\S+/g; print $f[4]' /proc/$pid/stat
/s
修饰符,并且你在这里复制了他们的错误。如果 Perl 正则表达式中没有 /s
修饰符,则 .
不匹配换行符,因此如果进程文件名中有换行符,则你的答案实际上无法正常工作,因此你的 Perl 答案并不比 awk
答案更好。将正则表达式末尾的 /g
改为 /gs
,那就是正确的答案。 - Ian D. Allen我为此编写了一个小脚本。
#!/bin/bash
MY_GROUP_ID=$1
A="$(ps -e -o pgid,pid= | grep [0-9])"
#printf "$A\n"
IFS=$'\n'
for i in $A; do
GROUP_ID=$(printf "$i" | awk -F ' ' '{print $1}')
PID=$(printf "$i" | awk -F ' ' '{print $2}')
if [ "$GROUP_ID" = "$MY_GROUP_ID" ]; then
printf "$PID\n"
fi
done
unset IFS
./test_script.sh (group ID you want to select for)
ps -e -o pgid,pid=
只是简单地打印出所有进程,每行的第一个值是其组ID,第二个值是其进程ID,两者之间用空格分隔。grep
删除不必要的标题行。for
结构自动使用空格字符对字符串进行分隔,但如果IFS变量设置为换行符,则使用这个新的空白字符进行分隔。这确保了每个迭代变量都是来自A
的一行。awk
获取第一个值-这是组ID,第二个值-这是PID。希望这能帮到你。对我来说很有效。一旦你理解了awk和ps的工作原理,它并不是很复杂。其余的只是解析。如果你想将PIDs作为数组传递而不是将其打印为新行,只需使用其他分隔符进行分隔,并创建一个全局字符串变量来保存所有的PIDs。
根据 man ps
,有四个参数与组有关:
-G grplist
Select by real group ID (RGID) or name. This selects the processes whose real group name or ID is in the grplist list. The real group ID identifies the group of the user who created the process, see getgid(2).
-g grplist
Select by session OR by effective group name. Selection by session is specified by many standards, but selection by effective group is the logical behavior that several other operating systems use. This ps will select by session when the list is
completely numeric (as sessionsare). Group ID numbers will work only when some group names are also specified. See the -s and --group options.
--Group grplist
Select by real group ID (RGID) or name. Identical to -G.
--group grplist
Select by effective group ID (EGID) or name. This selects the processes whose effective group name or ID is in grouplist. The effective group ID describes the group whose file access permissions are used by the process (see getegid(2)). The -g
option is often an alternative to --group.
因此,您可以使用getpgrp [pid-of-your-program]
获取程序的组ID,然后调用ps -G [group-if-of-your-program]
。
但这可能不是您想要的。进程组和形成树状结构的进程似乎是不同的事情。ppid是进程的父进程ID,您可能需要一些告诉您所有具有给定pid作为其ppid的pid的东西?我认为没有任何保证它与所有pid在同一个进程组中是相同的,实际上,如果每个进程只有一个进程组,它们就不能是。
如上所建议,pstree
应该帮助您了解正在发生的情况。 --show-pids
选项也将为您提供所有pid,这可能会有所帮助。
ps
命令会给你进程信息。然后你可以使用grep
命令来查找你需要的结果。 - Miguel-F