dt246813579 2016-08-17 22:59 采纳率: 0%
浏览 90
已采纳

Golang-将exec输出复制到缓冲区

I'm writing a function that exec's a program and returns stdout and stderr. It also has the option to display the output to the console. I'm clearly not waiting on something, as if I run the function twice in a row, the outputs are different. Here's a sample program, replace the dir var with a dir with a lot of files to fill up the buffers:

func main() {
    dir := "SOMEDIRECTORYWITHALOTOFFILES"
    out, err := run("ls -l "+dir, true)
    if err != nil {
        log.Fatalf("run returned %s", err)
    }
    log.Printf("Out: %s", out)
    out2, err := run("ls -l "+dir, false)
    if err != nil {
        log.Fatalf("run returned %s", err)
    }
    log.Printf("Out2: %s", out2)
    if out != out2 {
        log.Fatalf("Out mismatch")
    }
}

func run(cmd string, displayOutput bool) (string, error) {
    var command *exec.Cmd
    command = exec.Command("/bin/sh", "-c", cmd)
    var output bytes.Buffer

    stdout, err := command.StdoutPipe()
    if err != nil {
        return "", fmt.Errorf("Unable to setup stdout for command: %v", err)
    }
    go func() {
        if displayOutput == true {
            w := io.MultiWriter(os.Stdout, &output)
            io.Copy(w, stdout)
        } else {
            output.ReadFrom(stdout)
        }
    }()

    stderr, err := command.StderrPipe()
    if err != nil {
        return "", fmt.Errorf("Unable to setup stderr for command: %v", err)
    }
    go func() {
        if displayOutput == true {
            w := io.MultiWriter(os.Stderr, &output)
            io.Copy(w, stderr)
        } else {
            output.ReadFrom(stderr)
        }
    }()
    err = command.Run()
    if err != nil {
        return "", err
    }
    return output.String(), nil
}
  • 写回答

2条回答 默认 最新

  • duanfei1987 2016-08-18 01:45
    关注

    Here is a simplified and working revision of your example. Note that the test command was swapped out so that I could test within Windows and that your error checks have been omitted only for brevity.

    The key change is that a sync.WaitGroup is preventing the run function from printing the output and returning until the goroutine has indicated that it's finished.

    func main() {
        dir := "c:\\windows\\system32"
        command1 := exec.Command("cmd", "/C", "dir", "/s", dir)
        command2 := exec.Command("cmd", "/C", "dir", "/s", dir)
        out1, _ := run(command1)
        out2, _ := run(command2)
        log.Printf("Length [%d] vs [%d]
    ", len(out1), len(out2))
    }
    
    func run(cmd *exec.Cmd) (string, error) {
        var output bytes.Buffer
        var waitGroup sync.WaitGroup
    
        stdout, _ := cmd.StdoutPipe()
        writer := io.MultiWriter(os.Stdout, &output)
    
        waitGroup.Add(1)
        go func() {
            defer waitGroup.Done()
            io.Copy(writer, stdout)
        }()
    
        cmd.Run()
        waitGroup.Wait()
        return output.String(), nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?