Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect stdout pipe of child process in Go

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 program. One way to do this is with the cmd.Output() function, but this prints the stdout only after the process has exited. (That's a problem because this server-like program runs for a long time and I want to read the log output)

The variable out is of type io.ReadCloser and I don't know what I should do with it to achieve my task, and I can't find anything helpful on the web on this topic.

func main() {     cmd := exec.Command("/path/to/my/child/program")     out, err := cmd.StdoutPipe()     if err != nil {         fmt.Println(err)     }     err = cmd.Start()     if err != nil {         fmt.Println(err)     }     //fmt.Println(out)     cmd.Wait() }  

Explanation to the code: uncomment the Println function to get the code to compile, I know that Println(out io.ReadCloser) is not a meaningful function.
(it produces the output &{3 |0 <nil> 0} ) These two lines are just required to get the code to compile.

like image 601
mbert Avatar asked Jan 16 '12 01:01

mbert


2 Answers

Now I want to have the stdout of the child program in my terminal window where I started the parent program.

No need to mess with pipes or goroutines, this one is easy.

func main() {     // Replace `ls` (and its arguments) with something more interesting     cmd := exec.Command("ls", "-l")     cmd.Stdout = os.Stdout     cmd.Stderr = os.Stderr     cmd.Run() } 
like image 79
cmccabe Avatar answered Oct 13 '22 08:10

cmccabe


I believe that if you import io and os and replace this:

//fmt.Println(out) 

with this:

go io.Copy(os.Stdout, out) 

(see documentation for io.Copy and for os.Stdout), it will do what you want. (Disclaimer: not tested.)

By the way, you'll probably want to capture standard-error as well, by using the same approach as for standard-output, but with cmd.StderrPipe and os.Stderr.

like image 28
ruakh Avatar answered Oct 13 '22 09:10

ruakh