首页 > 解决方案 > 带有管道的 Multipe exec.Command 函数在 Golang 中没有输出

问题描述

我正在尝试在 golang 中执行程序并捕获第二个程序的输出以传递 Web 输出。单次执行不会造成任何问题,

//One exec
        t := time.Now()
        filename := "backup-" + hostname + "-" + t.Format(time.RFC3339) + ".img"
        w.Header().Set("Content-Disposition", "attachment; filename="+filename)
        // Set HTTP header befare Transfering data.
        w.Header().Set("Transfer-Encoding", "chunked")

        ddCommand := exec.Command("dd", fmt.Sprintf("if=%s", r.URL.Path[6:]))
        pipeIn, pipeWriter := io.Pipe()
        ddCommand.Stdout = pipeWriter
        ddCommand.Stderr = pipeWriter

        go writeCmdOutput(w, pipeIn)

        ddCommand.Run()
        pipeWriter.Close()

但是当我添加第二个程序来运行时,程序没有给出任何输出。

                // Get time and set headers
                t := time.Now()
                filename := "backup-" + hostname + "-" + t.Format(time.RFC3339) + ".img.gz"
                w.Header().Set("Content-Disposition", "attachment; filename="+filename)
                w.Header().Set("Transfer-Encoding", "chunked")

                pipeIn, pipeWriter := io.Pipe()

                ddCommand := exec.Command("dd", fmt.Sprintf("if=%s", r.URL.Path[9:]))
                gzipCommand := exec.Command("gzip ", "-1", "-")


                gzipCommand.Stdin, _ = ddCommand.StdoutPipe()

                gzipCommand.Stdout = pipeWriter
                go writeCmdOutput(w, pipeIn)

                _ = gzipCommand.Start()
                _ = ddCommand.Run()
                _ = gzipCommand.Wait()
                pipeWriter.Close()

但是当我尝试在没有管道的情况下运行命令时,执行会给出实时输出。示例命令

topCommand := exec.Command("top","-d 0.5", "-b", "-n 5")
awkCommand   := exec.Command("grep", "bash")

awkCommand.Stdin, _ = topCommand.StdoutPipe()
awkCommand.Stdout = os.Stdout

_ = awkCommand.Start()
_ = topCommand.Run()
_ = awkCommand.Wait()

那么我该如何解决这个问题呢?
更多细节项目源

标签: linuxgoexec

解决方案


推荐阅读