如何获得给定进程名称的PID [英] How to get pid given the process name

查看:116
本文介绍了如何获得给定进程名称的PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了各种论坛,在这里,我也可以找到针对Linux和Mac的一些答案,但是找不到针对Unix的解决方案,特别是Korn Shell的解决方案.

Hi I have searched various forums and here as well, I could find some answers for Linux and Mac but not able to find solution for Unix and specially Korn Shell.

如何从进程ID(pid)获取进程名称(命令名称)

How to get process name (command name) from process id (pid)

以下是我从SO中找到的参考 这也是

Below reference I found from SO This one And this one also

我在命令下面尝试了

ps -eaf | awk '{ print substr($0, index($0, $9)) }'

在给出时间而不是月份和日期的情况下,上述命令失败(因为在这种情况下,字符串中只有8列)

Above command is failing at a point where TIME is given rather than Month and Date (because in this case there will be only 8 columns in string)

任何建议都会有所帮助.

Any suggestion would help.

推荐答案

我认为使用 pgrep

I think it is easier to use pgrep

$ pgrep bluetoothd
441

否则,您可以使用awk:

ps -ef | awk '$8=="name_of_process" {print $2}'

例如,如果ps -ef的行类似于:

For example, if ps -efhas a line like:

root       441     1  0 10:02 ?        00:00:00 /usr/sbin/bluetoothd

然后ps -ef | awk '$8=="/usr/sbin/bluetoothd" {print $2}'返回441.

在ksh中找不到pgrep.另一个解决方案以防万一 以下是ps命令的输出jaggsmca325 7550 4752 0 Sep 11 pts/44 0:00 sqlplus dummy_user/dummy_password @ dummy_schema

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),无论其编号如何:

Let's check the last column ($NF), no matter its number:

$ ps -ef | awk '$NF=="/usr/sbin/bluetoothd" {print $2}'
441

如果要匹配的字符串不完全匹配,则可以使用~代替:

If you want to match not exact strings, you can use ~ instead:

$ ps -ef | awk '$NF~"bluetooth" {print $2}'
441
1906

这篇关于如何获得给定进程名称的PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆