Getting PID from lsof list
I have a react-native application and I want to write a script for start test version. I need to shotdown the :8081 port if it is alive. The command:
lsof -i :8081
kill -9 <PID>
The lsof getting back this result:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
chrome 2423 loow 127u IPv4 13749099 0t0 TCP localhost.localdomain:36650->localhost.localdomain:tproxy (ESTABLISHED)
qemu-syst 15091 loow 64u IPv4 13795587 0t0 TCP localhost.localdomain:43518->localhost.localdomain:tproxy (ESTABLISHED)
qemu-syst 15091 loow 66u IPv4 13795588 0t0 TCP localhost.localdomain:43520->localhost.localdomain:tproxy (ESTABLISHED)
qemu-syst 15091 loow 89u IPv4 13777485 0t0 TCP localhost.localdomain:40500->localhost.localdomain:tproxy (ESTABLISHED)
node 16210 loow 16u IPv6 13747716 0t0 TCP *:tproxy (LISTEN)
node 16210 loow 18u IPv6 13751322 0t0 TCP localhost.localdomain:tproxy->localhost.localdomain:36650 (ESTABLISHED)
node 16210 loow 19u IPv6 13798473 0t0 TCP localhost.localdomain:tproxy->localhost.localdomain:43518 (ESTABLISHED)
node 16210 loow 21u IPv6 13798475 0t0 TCP localhost.localdomain:tproxy->localhost.localdomain:43520 (ESTABLISHED)
node 16210 loow 27u IPv6 13777958 0t0 TCP localhost.localdomain:tproxy->localhost.localdomain:40500 (ESTABLISHED)
What exactly I need is the pid of the node service in this case 16210. How can I get it from lsof?
I tryed lsof -ti :8081
which return only the pids, but it's return back all of it. I tryed to extend it with grep: lsof -ti :8081 | grep node
, which return nothing.
So I only need the process id, to take it into the kill -9 $PID
.
Solution 1:
I think your whole approach is flawed, you should probably run your service under systemd (or wrap it in a systemV style start-stop script that records the PID) which would simplify stopping the correct service greatly.
Alternatively the conventional tool to find a specific process is pgrep
and the associated pkill
allows you to easily kill them:
pkill -9 -u node react-native-app-name
Having said that, to answer your literal question: in general the correct service processes to stop are the ones which provide the listener on that TCP port, i.e. restrict your lsof
output with -sTCP:LISTEN
lsof -i :8081 -sTCP:LISTEN |awk 'NR > 1 {print $2}' |xargs kill -15
Solution 2:
lsof -i :8081 | awk '{system("kill -9 " $2)}'
should do what you want. Be careful on a very high load system with a lot of short lived processes though. It could be that you kill the wrong process because sometimes the output of lsof proved not to be too reliable over time.
Solution 3:
Was going through this post. There are several ways suggested here to kill the process pulled using lsof.
Easiest way to kill -
kill $(lsof -ti:PORT)
This will kill all the process ids fetched in loop, automatically.