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

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

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


交互式爱情
浏览 155回答 1
1回答

jeck猫

如果您使用Commandgo从代码中运行 application.service ,例如:// Start a process:import "os/exec"cmd := exec.Command("code", ".")if err := cmd.Start(); err != nil {&nbsp; &nbsp; log.Fatal(err)}然后您可以使用以下代码从相同的代码中杀死它exec.Process:// Kill it:if err := cmd.Process.Kill(); err != nil {&nbsp; &nbsp; log.Fatal("failed to kill process: ", err)}否则,您需要读取进程 ID,然后将其杀死,go-ps将帮助完成此任务,这应该对您有所帮助。如果要终止 Web 服务器的应用程序,您需要获取 PID 并终止它,在某些情况下,应用程序在未释放端口时关闭,以下是获取 PID 并释放端口的典型命令(检查于苹果电脑)&nbsp; &nbsp; $ lsof -i tcp:8090&nbsp; &nbsp;OR lsof -i :<port>&nbsp; &nbsp; $ lsof -P | grep ':8090' | awk '{print $2}'&nbsp; // return PID number only&nbsp; &nbsp; $ ps ax | grep <PID> return status of the PID&nbsp; &nbsp; $ kill -QUIT <PID>// Or$ lsof -P | grep ':<port>' | awk '{print $2}' | xargs kill -9如果计划是从另一个网络服务器中杀死一个网络服务器,您可以创建一个路由来返回要关闭的服务器 PID,如下所示:func pid(w http.ResponseWriter, req *http.Request) {&nbsp; &nbsp; pid := fmt.Sprint(os.Getpid())&nbsp; &nbsp; fmt.Fprintf(w, pid)}然后在您的主应用程序中,您可以调用 PID 并终止服务器:&nbsp; &nbsp; resp, err := http.Get("http://localhost:port/pid")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; // handle error&nbsp; &nbsp; }&nbsp; &nbsp; defer resp.Body.Close()&nbsp; &nbsp; body, err := ioutil.ReadAll(resp.Body)&nbsp; &nbsp; byteToInt, _ := strconv.Atoi(string(body))&nbsp; &nbsp; proc, err := os.FindProcess(byteToInt)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalf("Error reading the process = %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; // Kill it:&nbsp; &nbsp; if err := proc.Kill(); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal("failed to kill process: ", err)&nbsp; &nbsp; }&nbsp; &nbsp; /* Enfore port cleaning&nbsp; &nbsp; &nbsp; &nbsp; proc, err = os.FindProcess(8090)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("Error reading the process = %v", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Kill it:&nbsp; &nbsp; &nbsp; &nbsp; if err := proc.Kill(); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("failed to kill process: ", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; */如果你打算使用这个练习,最好在创建服务器之前确保端口是空闲的,如下所示:&nbsp; &nbsp; port := "8090"&nbsp; &nbsp; byteToInt, _ := strconv.Atoi(port)&nbsp; &nbsp; proc, err := os.FindProcess(byteToInt)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalf("Error reading the process = %v", err)&nbsp; &nbsp; }&nbsp; &nbsp; // Kill it:&nbsp; &nbsp; if err := proc.Kill(); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("port ready for use")&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("port had been cleaned")&nbsp; &nbsp; }&nbsp; &nbsp; http.ListenAndServe(":"+port, nil)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go