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

发布于 2025-01-03 05:28:57 字数 282 浏览 4 评论 0原文

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

$ 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

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

$ 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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

浪菊怪哟 2025-01-10 05:28:57
alias kill3000="fuser -k -n tcp 3000"
alias kill3000="fuser -k -n tcp 3000"
在巴黎塔顶看东京樱花 2025-01-10 05:28:57

试试这个:

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

-t 标志就是你想要的:它显示 PID,而不是其他任何东西。

更新

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

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

假设您正在运行 bash。

更新

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

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

您可能希望将其设为 bash 函数。

Try this:

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

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

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.

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):

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

You might want to make this a bash function.

爱要勇敢去追 2025-01-10 05:28:57

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

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

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

... | xargs -r kill -9

Another option using using the original lsof command:

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

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

... | xargs -r kill -9
独木成林 2025-01-10 05:28:57

fuser -k 3000/tcp 也应该可以工作

fuser -k 3000/tcp should also work

我的鱼塘能养鲲 2025-01-10 05:28:57

怎么样

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

How about

alias kill3000="lsof -i:3000 | grep LISTEN | awk '{print $2}' | xargs kill -9"
鹿港巷口少年归 2025-01-10 05:28:57
fuser -n tcp 3000

将产生输出

3000/tcp:     <$pid>

所以你可以这样做:

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

Will yield the output of

3000/tcp:     <$pid>

So you could do:

fuser -n tcp 3000 | awk '{ print $2 }' | xargs -r kill
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文