Redirect stdout pipe of child process in Go

后端 未结 3 1016
长发绾君心
长发绾君心 2021-01-29 20:04

I\'m writing a program in Go that executes a server like program (also Go). Now I want to have the stdout of the child program in my terminal window where I started the parent p

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-29 20:32

    For those who don't need this in a loop, but would like the command output to echo into the terminal without having cmd.Wait() blocking other statements:

    package main
    
    import (
        "fmt"
        "io"
        "log"
        "os"
        "os/exec"
    )
    
    func checkError(err error) {
        if err != nil {
            log.Fatalf("Error: %s", err)
        }
    }
    
    func main() {
        // Replace `ls` (and its arguments) with something more interesting
        cmd := exec.Command("ls", "-l")
    
        // Create stdout, stderr streams of type io.Reader
        stdout, err := cmd.StdoutPipe()
        checkError(err)
        stderr, err := cmd.StderrPipe()
        checkError(err)
    
        // Start command
        err = cmd.Start()
        checkError(err)
    
        // Don't let main() exit before our command has finished running
        defer cmd.Wait()  // Doesn't block
    
        // Non-blockingly echo command output to terminal
        go io.Copy(os.Stdout, stdout)
        go io.Copy(os.Stderr, stderr)
    
        // I love Go's trivial concurrency :-D
        fmt.Printf("Do other stuff here! No need to wait.\n\n")
    }
    

提交回复
热议问题