Home >Backend Development >Golang >How to do non-blocking Read() on io.PipeRaeder in Golang

How to do non-blocking Read() on io.PipeRaeder in Golang

WBOY
WBOYforward
2024-02-10 11:10:17428browse

如何在 Golang 中对 io.PipeRaeder 进行非阻塞 Read()

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.

Question content

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))
}

Solution

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete