shell script to kill the process listening on port 3000? [duplicate]

两盒软妹~` 提交于 2019-11-30 06:12:08

问题


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

回答1:


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



回答2:


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.




回答3:


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



回答4:


How about

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



回答5:


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



回答6:


fuser -k 3000/tcp should also work



来源:https://stackoverflow.com/questions/9168392/shell-script-to-kill-the-process-listening-on-port-3000

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!