1 Star 0 Fork 0

Cruvie Kang / kk_go_kit

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
kk_system.go 1.19 KB
一键复制 编辑 原始数据 按行查看 历史
Cruvie 提交于 2024-01-26 18:01 . update log
//go:build linux || darwin
package kk_system
import (
"gitee.com/cruvie/kk_go_kit/kk_stage"
"log/slog"
"net"
"os/exec"
"strconv"
"strings"
)
// TerminatePort terminate the process which is using the port.
// port: :8080
func TerminatePort(port string) {
listener, err := net.Listen("tcp", port)
if err == nil {
err := listener.Close()
if err != nil {
slog.Error("listener close", kk_stage.NewLog(nil).Error(err).Args()...)
}
slog.Info("ok", port, "is not in use")
return
}
// 获取占用端口的进程ID
cmd := exec.Command("lsof", "-i", port)
output, err := cmd.Output()
if err != nil {
slog.Error("failed to execute command", kk_stage.NewLog(nil).Error(err).Args()...)
return
}
lines := strings.Split(string(output), "\n")
for _, line := range lines {
if strings.Contains(line, "LISTEN") {
fields := strings.Fields(line)
if len(fields) >= 2 {
pid, err := strconv.Atoi(fields[1])
if err == nil {
// 终止进程
killCmd := exec.Command("kill", "-9", strconv.Itoa(pid))
err = killCmd.Run()
if err != nil {
slog.Error("failed to terminate process", kk_stage.NewLog(nil).Error(err).Args()...)
return
}
}
}
}
}
}
1
https://gitee.com/cruvie/kk_go_kit.git
git@gitee.com:cruvie/kk_go_kit.git
cruvie
kk_go_kit
kk_go_kit
8ab331d8547b

搜索帮助

53164aa7 5694891 3bd8fe86 5694891