您可以在的输出中查看字段5th/proc/[pid]/stat
。
$ ps -ejH | grep firefox
3043 2683 2683 ? 00:00:21 firefox
$ < /proc/3043/stat sed -n '$s/.*) [^ ]* [^ ]* \([^ ]*\).*/\1/p'
2683
来自man proc
:
/proc/[pid]/stat
Status information about the process. This is used by ps(1). It is defined in /usr/src/linux/fs/proc/array.c.
The fields, in order, with their proper scanf(3) format specifiers, are:
pid %d The process ID.
comm %s The filename of the executable, in parentheses. This is visible whether or not the executable is swapped out.
state %c One character from the string "RSDZTW" where R is running, S is sleeping in an interruptible wait, D is waiting in
uninterruptible disk sleep, Z is zombie, T is traced or stopped (on a signal), and W is paging.
ppid %d The PID of the parent.
pgrp %d The process group ID of the process.
session %d The session ID of the process.
请注意,您不能使用:
awk '{print $5}'
因为该文件不是空白的分隔列表。第二个字段(进程名称可能包含空格或什至换行符)。例如,大多数的线程firefox
通常在名称中都带有空格字符。
因此,您需要在最后一个出现的)
字符之后打印第三个字段。
awk '{print $5}'
由于进程名称(第二个字段)可能包含空格或换行符,因此不能保证为您提供正确的答案。