golang执行linux

2022/8/11 5:23:04

本文主要是介绍golang执行linux,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

func copyAndCapture(w io.Writer, r io.Reader) ([]byte, error) {
    var out []byte
    buf := make([]byte, 1024, 1024)
    for {
        n, err := r.Read(buf[:])
        if n > 0 {
            d := buf[:n]
            out = append(out, d...)
            os.Stdout.Write(d)
        }
        if err != nil {
            // Read returns io.EOF at the end of file, which is not an error for us
            if err == io.EOF {
                err = nil
            }
            return out, err
        }
    }
    // never reached
    panic(true)
    return nil, nil
}
func main() {
    cmd := exec.Command("ls", "-lah")
    var stdout, stderr []byte
    var errStdout, errStderr error
    stdoutIn, _ := cmd.StdoutPipe()
    stderrIn, _ := cmd.StderrPipe()
    cmd.Start()
    go func() {
        stdout, errStdout = copyAndCapture(os.Stdout, stdoutIn)
    }()
    go func() {
        stderr, errStderr = copyAndCapture(os.Stderr, stderrIn)
    }()
    err := cmd.Wait()
    if err != nil {
        log.Fatalf("cmd.Run() failed with %s\n", err)
    }
    if errStdout != nil || errStderr != nil {
        log.Fatalf("failed to capture stdout or stderr\n")
    }
    outStr, errStr := string(stdout), string(stderr)
    fmt.Printf("\nout:\n%s\nerr:\n%s\n", outStr, errStr)
}

 



这篇关于golang执行linux的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程