Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stream stdout from other program without for loop

Tags:

go

I have a program that compile and run another program and pipe the stdout to itself for printing, since that program doesn't terminate so I need to stream it's stdout

// boilerplate ommited

func stream(stdoutPipe io.ReadCloser) {
    buffer := make([]byte, 100, 1000)
    for ;; {
        n, err := stdoutPipe.Read(buffer)
        if err == io.EOF {
            stdoutPipe.Close()
            break
        }
        buffer = buffer[0:n]
        os.Stdout.Write(buffer)
    }
}

func main() {
    command := exec.Command("go", "run", "my-program.go")
    stdoutPipe, _ := command.StdoutPipe()

    _ = command.Start()

    go stream(stdoutPipe)

    do_my_own_thing()

    command.Wait()
}

It works, but how do I do the same without repeatedly checking with a for loop, is there a library function that does the same thing?

like image 475
yngccc Avatar asked Apr 09 '26 19:04

yngccc


1 Answers

You can give the exec.Cmd an io.Writer to use as stdout. The variable your own program uses for stdout (os.Stdout) is also an io.Writer.

command := exec.Command("go", "run", "my-program.go")
command.Stdout = os.Stdout
command.Start()
command.Wait()
like image 123
Stephen Weinberg Avatar answered Apr 12 '26 13:04

Stephen Weinberg