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

WBOY
Release: 2024-02-10 11:10:17
forward
389 people have browsed it

如何在 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))
}

Copy after login

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

}

Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!