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
.
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.
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.
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.
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
.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With