在用exec包调用的其他进程后如何关闭结束,可以使用context包的机制进行管理,context包的使用详见:https://godoc.org/context
exec.CommandContext方发实现了context,通过context可以对exec启动的进程结束。
隐藏程序自身黑窗口的方法:go build -ldflags="-H windows"
隐藏子进程黑窗口的方法:
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
package main
import (
"context"
"fmt"
"os"
"os/exec"
"syscall"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
cmd := exec.CommandContext(ctx, "./b")
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
cmd.Stdout = os.Stdout
cmd.Start()
time.Sleep(10 * time.Second)
fmt.Println("退出程序中...", cmd.Process.Pid)
cancel()
cmd.Wait()
}
//有网友说
不用这么麻烦啊,直接cmd.Process.Kill()就好
转自
https://mp.weixin.qq.com/s?__biz=MzAxMzc4Mzk1Mw==&mid=2649836709&idx=1&sn=dc1eb9d75e544ca1b6e98c464fc73265&chksm=8398aa5bb4ef234d732b6e8a8f48c07520329ed3ff0e657dccb3c90af5b44e3dfb0749ef2a34&mpshare=1&scene=1&srcid=1031BJbRDke2YHPGja6cFTHR#rd
最近在写一个应用,下面是用到的代码,网上也有挺多的网友遇到这种问题,下面是我的解决方法,分享一下.
使用方法,想exec.Command的时候使用SetPgid设置进程组,杀的时候使用KillAll杀死全部调用产生的进程
代码实现:
Linux处理方法:
package system
import (
"syscall"
)
func SetPgid(pid, pgid int) error {
return syscall.Setpgid(pid, pgid)
}
func GetPPids(pid int) ([]int, error) {
return []int{}, nil
}
func Kill(pids []uint32) {
for _, pid := range pids {
syscall.Kill(int(pid), syscall.SIGKILL)
}
}
func KillAll(pid int) error {
return syscall.Kill(pid-(pid*2), syscall.SIGKILL)
}
go语言exec包调用shell命令
yypnathan · 2016-08-18 17:00:03 · 9431 次点击 · 预计阅读时间不到 1 分钟 · 4分钟之前 开始浏览
这是一个创建于 2016-08-18 17:00:03 的文章,其中的信息可能已经有所发展或是发生改变。
工程中需要用到ffmpeg,想直接用exec包调用shell命令。本来以为很简单,结果折腾了一下午,最后查到了解决方案。
假如之前执行报错的语句为:
cmd := exec.Command("echo", "'helloworld!'")
out, err := cmd.Output()
那么改为:
c := "echo hello world"
cmd := exec.Command("sh", "-c", c)
out, err := cmd.Output()
即可!
感谢万能的stack overflow
nulijiabei 2016-07-05 14:44
cmd := exec.Command(sw, name)
cmd.Process.Pid
cmd.Process.Kill()
本文介绍如何在Go语言中使用exec包调用Shell命令并管理进程,包括如何隐藏窗口、设置进程组、及优雅地结束进程。同时,提供了解决常见错误的方法,如正确构造命令以避免报错。

被折叠的 条评论
为什么被折叠?



