Linux shell脚本杀死监听端口3000的进程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9168392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 04:25:49  来源:igfitidea点击:

shell script to kill the process listening on port 3000?

linuxbashsocketskill

提问by Jonathan

I want to define a bash alias named kill3000to automate the following task:

我想定义一个名为 bash 别名以kill3000自动执行以下任务:

$ lsof -i:3000

COMMAND   PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
ruby    13402 zero    4u  IPv4 2847851      0t0  TCP *:3000 (LISTEN)

$ kill -9 13402

采纳答案by SamB

alias kill3000="fuser -k -n tcp 3000"

回答by synthesizerpatel

fuser -n tcp 3000

Will yield the output of

将产生的输出

3000/tcp:     <$pid>

So you could do:

所以你可以这样做:

fuser -n tcp 3000 | awk '{ print  }' | xargs -r kill

回答by Niklas B.

Another option using using the original lsofcommand:

使用原始lsof命令的另一个选项:

lsof -n -i:3000 | grep LISTEN | awk '{ print  }' | uniq | xargs kill -9

If you want to use this in a shell script, you could add the -rflag to xargsto handle the case where no process is listening:

如果你想在 shell 脚本中使用它,你可以添加-r标志xargs来处理没有进程正在侦听的情况:

... | xargs -r kill -9

回答by dgw

How about

怎么样

alias kill3000="lsof -i:3000 | grep LISTEN | awk '{print }' | xargs kill -9"

回答by Hai Vu

Try this:

尝试这个:

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

The -t flag is what you want: it displays PID, and nothing else.

-t 标志是你想要的:它显示 PID,没有别的。

UPDATE

更新

In case the process is not found and you don't want to see error message:

如果未找到该进程并且您不想看到错误消息:

    kill -9 $(lsof -i:3000 -t) 2> /dev/null

Assuming you are running bash.

假设您正在运行 bash。

UPDATE

更新

Basile's suggestion is excellent: we should first try to terminate the process normally will kill -TERM, if failed, then kill -KILL(AKA kill -9):

Basile 的建议非常好:我们应该首先尝试终止进程,通常会kill -TERM,如果失败,则kill -KILL(AKA kill -9):

    pid=$(lsof -i:3000 -t); kill -TERM $pid || kill -KILL $pid

You might want to make this a bash function.

您可能想让它成为一个 bash 函数。

回答by Dmitriusan

fuser -k 3000/tcpshould also work

fuser -k 3000/tcp也应该工作