unix - 给定进程名称如何获取pid

标签 unix ksh pid ps

嗨,我已经搜索了各种论坛,在这里也可以找到一些适用于 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/

相关文章:

unix - 邮件中存在多个 DKIM 签名?

c - 为什么 memcmp() 相差 1 时返回 256?

bash - 为什么 $$ 返回与父进程相同的 id?

mysql - 错误!服务器在 El capitan 上没有更新 PID 文件就退出了

linux - Unix - 如何对一个词使用 cut -d

linux - 如何通过换行符或字符读取输入?

linux - 使用循环解析ksh中的长参数和短参数

linux - 检查特定用户名密码过期脚本

c - popen 与 KornShell 安全性

c++ - (Visual C++) 从线程获取 PID