Find (and kill) process locking port 3000 on Mac

2019-01-02 16:10发布

How do I find processes that listens to/uses my tcp ports? I'm on mac os x.

Sometimes, after a crash or some bug, my rails app is locking port 3000. I can't find it using ps -ef... How do I find the stupid thing and kill it, brutally... ?

When doing

rails server

I get

Address already in use - bind(2) (Errno::EADDRINUSE)

2014 update:

To complete some of the answers below: After executing the kill commands, deleting the pid file might be necessary rm ~/mypath/myrailsapp/tmp/pids/server.pid

标签: macos process
24条回答
余生无你
2楼-- · 2019-01-02 16:52

Execute in command line on OS-X El Captain:

kill -kill `lsof -t -i tcp:3000`

Terse option of lsof returns just the PID.

查看更多
回忆,回不去的记忆
3楼-- · 2019-01-02 16:53

Add to ~/.bash_profile:

function killTcpListen () {
  kill -QUIT $(sudo lsof -sTCP:LISTEN -i tcp:$1 -t)
}

Then source ~/.bash_profile and run

killTcpListen 8080

查看更多
唯独是你
4楼-- · 2019-01-02 16:55

Find:

[sudo] lsof -i :3000

Kill:

kill -9 <PID>
查看更多
查无此人
5楼-- · 2019-01-02 16:55

Nothing above worked for me. Anyone else with my experience could try the following (worked for me):

Run:

lsof -i :3000 (where 3000 is your current port in use)

then check status of the reported PID :

ps ax | grep <PID>

finally, "begone with it":

kill -QUIT <PID>
查看更多
闭嘴吧你
6楼-- · 2019-01-02 16:56

You can use lsof -i:3000.

That is "List Open Files". This gives you a list of the processes and which files and ports they use.

查看更多
低头抚发
7楼-- · 2019-01-02 16:56

TL;DR:

lsof -ti tcp:3000 -sTCP:LISTEN | xargs kill

If you're in a situation where there are both clients and servers using the port, e.g.:

$ lsof -i tcp:3000
COMMAND     PID         USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
node       2043 benjiegillam   21u  IPv4 0xb1b4330c68e5ad61      0t0  TCP localhost:3000->localhost:52557 (ESTABLISHED)
node       2043 benjiegillam   22u  IPv4 0xb1b4330c8d393021      0t0  TCP localhost:3000->localhost:52344 (ESTABLISHED)
node       2043 benjiegillam   25u  IPv4 0xb1b4330c8eaf16c1      0t0  TCP localhost:3000 (LISTEN)
Google    99004 benjiegillam  125u  IPv4 0xb1b4330c8bb05021      0t0  TCP localhost:52557->localhost:3000 (ESTABLISHED)
Google    99004 benjiegillam  216u  IPv4 0xb1b4330c8e5ea6c1      0t0  TCP localhost:52344->localhost:3000 (ESTABLISHED)

then you probably don't want to kill both.

In this situation you can use -sTCP:LISTEN to only show the pid of processes that are listening. Combining this with the -t terse format you can automatically kill the process:

lsof -ti tcp:3000 -sTCP:LISTEN | xargs kill
查看更多
登录 后发表回答