linux - 如何仅在端口打开时终止在端口上运行的进程?

标签 linux bash unix

目前,我可以通过以下方式终止在端口上运行的进程:

//other scripts that should be executed
...........................
sudo kill $( sudo lsof -i:9005 -t )
...........................
//other scripts that should be executed

现在,我想首先测试端口 9005 是否真的打开,然后才尝试杀死它。如果端口没有打开,我不想执行 kill 脚本。我想确保无论端口是打开还是关闭,后续脚本都会执行。所以,我正在寻找类似的东西:

//other scripts that should be executed
.............
<test-if-port-9005-is-open>  && sudo kill $( sudo lsof -i:9005 -t )
.............
// other scripts that should be executed

我怎样才能做到这一点?

最佳答案

你可以这样做:

nc -zv 127.0.0.1 9005 && sudo kill $( sudo lsof -i:9005 -t )

如果 tcp 连接在提供的端口上成功,它会终止进程。然后它继续前进。在 macOS High Sierra 上测试过。

关于linux - 如何仅在端口打开时终止在端口上运行的进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47467248/

相关文章:

linux - mv/重命名具有公共(public)部分但文件模式未知的文件

linux - 在 solaris 上的 heredoc 中转义换行符

linux - 使用 systemd 登录后启动 autofs

linux - 用于 BASH 着色和 inputrc 的神秘语法

linux - 如何比较两个 DateTime 字符串并以小时为单位返回差异? ( bash shell )

bash - 使用 ./dot-slash 运行 shell 脚本

python - pip 安装需要 tls/ssl

linux - Bash 脚本在不创建临时文件的情况下保存值

linux - 为什么 read 在 bash 中抛出错误但工作正常?

c++ - 如何在没有 sysfs/library 的情况下控制 GPIO