-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
49 lines (43 loc) · 1.32 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import (
"fmt"
"runtime"
"os/exec"
"syscall"
"os"
"strconv"
)
func main() {
if len(os.Args) < 2 {
os.Stderr.WriteString(fmt.Sprintf("Error: port argument missing.\n"))
os.Exit(1);
}
port := os.Args[1]
if _, err := strconv.Atoi(port); err != nil {
os.Stderr.WriteString(fmt.Sprintf("Error: port argument is not a number.\n"))
os.Exit(1);
}
if runtime.GOOS == "windows" {
command := fmt.Sprintf("(Get-NetTCPConnection -LocalPort %s).OwningProcess -Force", port)
exec_cmd(exec.Command("Stop-Process", "-Id", command))
} else {
command := fmt.Sprintf("lsof -i tcp:%s | grep LISTEN | awk '{print $2}' | xargs kill -9", port)
exec_cmd(exec.Command("bash", "-c", command))
}
}
// Execute command and return exited code.
func exec_cmd(cmd *exec.Cmd) {
var waitStatus syscall.WaitStatus
if err := cmd.Run(); err != nil {
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("Error: %s\n", err.Error()))
}
if exitError, ok := err.(*exec.ExitError); ok {
waitStatus = exitError.Sys().(syscall.WaitStatus)
fmt.Printf("Error during killing (exit code: %s)\n", []byte(fmt.Sprintf("%d", waitStatus.ExitStatus())))
}
} else {
waitStatus = cmd.ProcessState.Sys().(syscall.WaitStatus)
fmt.Printf("Port successfully killed (exit code: %s)\n", []byte(fmt.Sprintf("%d", waitStatus.ExitStatus())))
}
}