Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the PID from an lsof.

Tags:

bash

terminal

Given the following command lsof -i:1025 I get:

COMMAND   PID USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
ruby    12345 john   11u  IPv4 0xb2f4161230e18fd57      0t0  TCP localhost:foobar (LISTEN)

I am trying to write a script to get that PID (12345) and kill it. At the moment I have to run lsof -i:1025, get that PID and then run kill -9 12345.

like image 959
Zack Avatar asked Nov 09 '15 18:11

Zack


People also ask

How do you find the lsof pid?

Should do it. The 3rd line runs lsof using the -F option to get just the pid, with a leading p . The next line drops the leading p from the output of lsof and uses the result as the pid in a kill command.

What is pid lsof?

lsof -p process ID. Files opened by all other PID: As the above-given figure command lists out the files opened by a particular process ID. In the same way, you can use below command option to find out the list of files which are not opened by a particular process ID.

How do I find the pid of a process in Linux?

The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.


2 Answers

The lsof(8) man page says:

   -t       specifies that lsof should produce terse output with process
            identifiers only and no header - e.g., so that the output
            may be piped to kill(1).  -t selects the -w option.

You can use lsof -t -i:1025 | xargs kill -9.

like image 76
fabianopinto Avatar answered Sep 27 '22 22:09

fabianopinto


And furthermore from @blm's and @Mosh Feu's answers:

lsof -i:1337 -Fp | head -n 1 | sed 's/^p//' | xargs kill

is what ended up doing the trick for me.

I recommend adding this as a bash function and aliasing it

alias kbp='killByPort'
killByPort() {
  lsof -i:$1 -Fp | head -n 1 | sed 's/^p//' | xargs kill
}
like image 20
rsmets Avatar answered Sep 27 '22 22:09

rsmets