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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With