一.安装Cygwin

1
2
3
4
5
//下载
https://www.cygwin.com
//安装配置参考
https://jingyan.baidu.com/article/455a99507c0b78a166277809.html
https://www.douban.com/note/723078223/

终端校验
在这里插入图片描述

二.golang脚本执行Linux命令

在这里插入图片描述

1
2
3
4
5
6
7
8
9
var (
    cmd *exec.Cmd
    err error
)

//执行Linux命令
cmd = exec.Command("D:\\cygwin64\\bin\\bash.exe", "-c", "df -h")
err = cmd.Run()
fmt.Println(err)

获取子进程输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var (
    cmd *exec.Cmd
    output []byte
    err error
)
//生成Cmd
cmd = exec.Command("D:\\cygwin64\\bin\\bash.exe","-c","sleep 5;ls -l")

//执行命令,捕获子进程的输出(pipe)
if output, err = cmd.CombinedOutput();err !=nil{
    fmt.Println(err)
    return
}

//打印子进程的输出
fmt.Println(string(output))

程序运行期间终止程序运行

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
@FileName: main.go
@Time    : 2020/4/20 7:12
@Author  : Cocktail_py
*/
package main

import (
    "context"
    "fmt"
    "os/exec"
    "time"
)

//进程的输入赋值给结构体
type result struct {
    err error
    output []byte
}


func main() {
    // 执行1个cmd,让它在协程里去执行,让它执行2秒;sleep 2;echo hello;
    // 1秒的时候,我们杀死cmd
    var (
        ctx        context.Context
        cancelFunc context.CancelFunc
        cmd *exec.Cmd
        resultChan chan *result
        res *result
    )
    //创建一个结果队列
    resultChan = make(chan *result,1000)

    //context: chan byte
    //cancelFunc: close(chan byte)
    ctx, cancelFunc = context.WithCancel(context.TODO())

    go func() {
        var (
            output []byte
            err error
        )
        cmd = exec.CommandContext(ctx, "D:\\cygwin64\\bin\\bash.exe", "-c", "sleep 2;")

        //select {case <- ctx.Done(): }
        //kill pid, 进程ID, 杀死子进程

        //执行任务,捕获输出
        output, err = cmd.CombinedOutput()

        //把任务输出结果,传给main协程
        resultChan <- &result{
            err:    err,
            output: output,
        }

    }()

    //继续往下走
    time.Sleep(1 * time.Second)

    //取消上下文
    cancelFunc()

    //在main协程里,等子协程的退出,并打印任务执行结果
    res =<- resultChan
    fmt.Println(res.err)
}