Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

unix - How to get pid given the process name

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.

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

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

I tried below command

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think it is easier to use pgrep

$ pgrep bluetoothd
441

Otherwise, you can use awk:

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

For example, if ps -efhas a line like:

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

Then ps -ef | awk '$8=="/usr/sbin/bluetoothd" {print $2}' returns 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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...