Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get pid given the process name

Tags:

unix

ksh

pid

ps

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.

like image 578
gahlot.jaggs Avatar asked Sep 12 '13 13:09

gahlot.jaggs


People also ask

How do you find the PID of a process in python?

We can get the pid for the current process via the os. getpid() function. We may also get the pid for the parent process via the os. getppid() function.

How do I find the PID of a file?

You'll usually find the PID files for daemonized processes in /var/run/ on Redhat/CentOS-style systems. Short of that, you can always look in the process init script. For instance, the SSH daemon is started with the script in /etc/init.


2 Answers

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 
like image 65
fedorqui 'SO stop harming' Avatar answered Oct 06 '22 10:10

fedorqui 'SO stop harming'


You can use pidof to get all IDs of running processes with the name p_name:

pidof p_name | tr ' ' '\n' (for a vertical listing)

pkill p_name - kill all processes whith the name p_name

Make sure that you have the permission to kill them all :)

like image 40
k-messaoudi Avatar answered Oct 06 '22 10:10

k-messaoudi