Home >Backend Development >Golang >How to do non-blocking Read() on io.PipeRaeder in Golang
In Golang, io.PipeReader is a commonly used reader, but its Read() method blocks the execution of the program when there is no data to read. So how to implement non-blocking reading of io.PipeReader? PHP editor Xiaoxin provides you with a solution. By using select and goroutine, we can achieve non-blocking reading of io.PipeReader, thereby improving the responsiveness and concurrency of the program. The following will introduce in detail how to implement this function and give sample code.
I have the following code. After 5 seconds, the executable will send some text to stdout. Therefore, in.readline() will block until data is received. How can I set a timeout for readline() or execute it in a non-blocking manner?
package main import ( "bufio" "fmt" "io" "os/exec" ) func main() { cmd := exec.Command("/path/to/executable") stdoutReader, stdoutWriter := io.Pipe() cmd.Stdout = stdoutWriter cmd.Start() in := bufio.NewReader(stdoutReader) b, _, _ := in.ReadLine() fmt.Println(string(b)) }
Thank you for your comment. I see.
package main import ( "bufio" "fmt" "io" "os/exec" "time" ) func main() { ch := make(chan []byte) cmd := exec.Command("/path/to/executable") stdoutReader, stdoutWriter := io.Pipe() cmd.Stdout = stdoutWriter if err := cmd.Start(); err != nil { return } in := bufio.NewReader(stdoutReader) go func() { b, _, _ := in.ReadLine() ch <- b }() complete := false for !complete { select { case s := <-ch: fmt.Println(string(s)) complete = true case <-time.After(time.Second * 5): fmt.Println("timeout") complete = true } } }
The above is the detailed content of How to do non-blocking Read() on io.PipeRaeder in Golang. For more information, please follow other related articles on the PHP Chinese website!