嗨,我已经搜索了各种论坛,在这里也可以找到一些适用于 Linux 和 Mac 的答案,但无法找到适用于 Unix 和特别是 Korn Shell 的解决方案。
如何从进程id(pid)中获取进程名(命令名)
下面是我从 SO 找到的引用
This one
And this one also
我试过下面的命令
ps -eaf | awk '{ print substr($0, index($0, $9)) }'
上面的命令在给出 TIME 而不是 Month 和 Date 的地方失败(因为在这种情况下,字符串中只有 8 列)
任何建议都会有所帮助。
最佳答案
我觉得用起来更方便 pgrep
$ pgrep bluetoothd
441
否则,您可以使用
awk
:ps -ef | awk '$8=="name_of_process" {print $2}'
例如,如果
ps -ef
有这样一行:root 441 1 0 10:02 ? 00:00:00 /usr/sbin/bluetoothd
然后
ps -ef | awk '$8=="/usr/sbin/bluetoothd" {print $2}'
返回 441
.In ksh pgrep is not found. and the other solution is failing in case below is output from ps command jaggsmca325 7550 4752 0 Sep 11 pts/44 0:00 sqlplus dummy_user/dummy_password@dummy_schema
让我们检查最后一列(
$NF
),不管它的数字是多少:$ ps -ef | awk '$NF=="/usr/sbin/bluetoothd" {print $2}'
441
如果你想匹配不精确的字符串,你可以使用
~
反而:$ ps -ef | awk '$NF~"bluetooth" {print $2}'
441
1906
关于unix - 给定进程名称如何获取pid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18765298/