-3

我知道我们可以使用https://golang.org/pkg/os/exec/#example_Cmd_Run从 Go 代码启动另一个应用程序

有没有办法从我的代码中关闭/关闭另一个应用程序/进程,例如,如果它正在运行,我想关闭 MS excel。

4

1 回答 1

0

如果您使用Commandgo从代码中运行 application.service ,例如:

// Start a process:
import "os/exec"
cmd := exec.Command("code", ".")
if err := cmd.Start(); err != nil {
    log.Fatal(err)
}

然后您可以使用以下代码从相同的代码中杀死它exec.Process

// Kill it:
if err := cmd.Process.Kill(); err != nil {
    log.Fatal("failed to kill process: ", err)
}

否则,您需要读取进程 ID,然后将其杀死,go-ps将帮助完成此任务,应该对您有所帮助。

如果要终止 Web 服务器的应用程序,您需要获取 PID 并终止它,在某些情况下,应用程序在未释放端口时关闭,以下是获取 PID 并释放端口的典型命令(检查于苹果电脑)

    $ lsof -i tcp:8090   OR lsof -i :<port>
    $ lsof -P | grep ':8090' | awk '{print $2}'  // return PID number only
    $ ps ax | grep <PID> return status of the PID
    $ kill -QUIT <PID>
// Or
$ lsof -P | grep ':<port>' | awk '{print $2}' | xargs kill -9

如果计划是从另一个网络服务器中杀死一个网络服务器,您可以创建一个路由来返回要关闭的服务器 PID,如下所示:

func pid(w http.ResponseWriter, req *http.Request) {

    pid := fmt.Sprint(os.Getpid())
    fmt.Fprintf(w, pid)
}

然后在您的主应用程序中,您可以调用 PID 并终止服务器:

    resp, err := http.Get("http://localhost:port/pid")
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    byteToInt, _ := strconv.Atoi(string(body))
    proc, err := os.FindProcess(byteToInt)
    if err != nil {
        log.Fatalf("Error reading the process = %v", err)
    }
    // Kill it:
    if err := proc.Kill(); err != nil {
        log.Fatal("failed to kill process: ", err)
    }

    /* Enfore port cleaning
        proc, err = os.FindProcess(8090)
        if err != nil {
            fmt.Printf("Error reading the process = %v", err)
        }
        // Kill it:
        if err := proc.Kill(); err != nil {
            fmt.Printf("failed to kill process: ", err)
        }
    */

如果你打算使用这个练习,最好在创建服务器之前确保端口是空闲的,如下所示:

    port := "8090"
    byteToInt, _ := strconv.Atoi(port)
    proc, err := os.FindProcess(byteToInt)
    if err != nil {
        log.Fatalf("Error reading the process = %v", err)
    }
    // Kill it:
    if err := proc.Kill(); err != nil {
        fmt.Println("port ready for use")
    } else {
        fmt.Println("port had been cleaned")
    }

    http.ListenAndServe(":"+port, nil)
于 2020-11-14T12:00:54.767 回答