为了账号安全,请及时绑定邮箱和手机立即绑定

从我的代码中关闭另一个程序/服务

从我的代码中关闭另一个程序/服务

Go
交互式爱情 2022-07-11 17:00:15
我知道我们可以使用https://golang.org/pkg/os/exec/#example_Cmd_Run从 Go 代码启动另一个应用程序有没有办法从我的代码中关闭/关闭另一个应用程序/进程,例如,如果它正在运行,我想关闭 MS excel。
查看完整描述

1 回答

?
jeck猫

TA贡献1909条经验 获得超7个赞

如果您使用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)


查看完整回答
反对 回复 2022-07-11
  • 1 回答
  • 0 关注
  • 150 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号