如何查找(并终止)侦听/使用TCP端口的进程?我在macOS上。

有时,在崩溃或一些错误之后,我的Rails应用程序会锁定端口3000。我用ps-ef找不到它。。。

运行时

rails server

我明白了

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

停止Node.js进程时也会出现同样的问题。即使在进程停止且应用程序停止运行后,端口3000仍被锁定。再次启动应用程序时

Address already in use (Errno::EADDRINUSE)

当前回答

步骤1:查找正在运行的服务器:ps aux|grep美洲狮第二步:杀死那些服务器杀死-9[服务器编号]

其他回答

下面是一个helper bash函数,用于按名称或端口杀死多个进程

fkill() {
  for i in $@;do export q=$i;if [[ $i == :* ]];then lsof -i$i|sed -n '1!p';
  else ps aux|grep -i $i|grep -v grep;fi|awk '{print $2}'|\
  xargs -I@ sh -c 'kill -9 @&&printf "X %s->%s\n" $q @';done
}

用法:

$ fkill [process name] [process port]

例子:

$ fkill someapp :8080 node :3333 :9000

在端口上终止进程的方法之一是使用python库:freeport(https://pypi.python.org/pypi/freeport/0.1.9) . 安装后,只需:

# install freeport
pip install freeport

# Once freeport is installed, use it as follows
$ freeport 3000
Port 3000 is free. Process 16130 killed successfully

在.bash_profile中,创建终止3000进程的快捷方式:

terminate(){
  lsof -P | grep ':3000' | awk '{print $2}' | xargs kill -9 
}

然后,如果被阻止,调用$terminate。

只在终端上写入

sudo kill -9 $(lsof -i :3000 -t)

希望,这是工作。

查找并杀死:

这条命令行很简单,工作正常。

kill -9 $(lsof -ti tcp:3000)