首页 > 解决方案 > close a port from go code - not cmd to lsof

问题描述

Env 
os: MacOS
go version: go1.14.3 darwin/amd64

I have a grpc server running and it does not always close the port (out of my control).

Do you know if it is possible to close a port from code?

It looks like you can do - but I need the pid?

err := syscall.Kill(<PID>, syscall.SYS_KILL)
if err == nil {
    fmt.Println("success")
}

I use to have this working in Powershell, but would like to move it to Go:

# lsof -ti tcp:$Port | xargs kill
Write-Host "Before: lsof -i :$Port"
lsof -i :$Port
$OutputVariable = (lsof -i :$Port | awk 'NR==2 { print $2 }') | Out-String
Write-Host "Process killed: $OutputVariable"
Stop-Process -Id $OutputVariable
Write-Host "After: lsof -i :$Port"
lsof -i :$Port

标签: go

解决方案


推荐阅读