golang 执行 command

alt

你并不是一无所有,至少你有肉。

代码

golang中会经常遇到要 fork 子进程的需求。go 标准库为我们封装了 os/exec标准包,当我们要运行外部命令时应该优先使用这个库。这里我简单结合context 和 Cmd 模块写一个通用的执行 command 方法。代码如下:

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
package main

import (
"context"
"os/exec"
"syscall"
)

func RunCmd(ctx context.Context, cmd *exec.Cmd) error {
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}

if err := cmd.Start(); err != nil {
return err
}

errCh := make(chan error, 1)
go func() {
errCh <- cmd.wait()< span>
}()

done := ctx.Done()
for {
select {
case <-done:< span>
done = nil
pid := cmd.Process.Pid
if err := syscall.Kill(-1*pid, syscall.SIGKILL); err != nil {
return err
}
case err := <-errch:< span>
if done == nil {
return ctx.Err()
} else {
return err
}
}
}
}

说明

  • 可以通过 context 控制命令执行, 调用方可以调用cancel 或者设置超时控制命令执行生命周期
  • 如果进程执行失败, 应当 kill 整个进程组, 防止该进程 fork 的子进程逃逸
-------------本文结束感谢您的阅读-------------

本文标题:golang 执行 command

文章作者:Wang Jiemin

发布时间:2019年04月20日 - 16:04

最后更新:2019年04月20日 - 16:04

原始链接:https://jiemin.wang/2019/04/20/go-command/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%