How to Check for Data in Stdin without Blocking in Go?

Mary-Kate Olsen
Release: 2024-10-31 11:16:29
Original
663 people have browsed it

How to Check for Data in Stdin without Blocking in Go?

Checking for Data in Stdin with Go

In Go, interacting with standard input (stdin) is often a crucial task when working with commands and pipelines. However, determining if stdin has data without blocking the program's execution can be challenging.

The os.Stdin file object represents stdin, and it possesses capabilities similar to other file objects in Go. This allows us to leverage the Stat function to gather information about stdin, including its size.

To ascertain whether stdin contains data, we can check its size using the following code:

<code class="go">func main() {
    file := os.Stdin
    fi, err := file.Stat()
    if err != nil {
        fmt.Println("file.Stat()", err)
    }
    size := fi.Size()
    if size > 0 {
        fmt.Printf("%v bytes available in Stdin\n", size)
    } else {
        fmt.Println("Stdin is empty")
    }
}</code>
Copy after login

When this code is compiled into an executable, it can be used as a filter to process input piped into stdin. For example, executing the command echo test | ./executable would print "5 bytes available in Stdin" to the console, indicating that stdin contains data. Conversely, running ./executable without any input would display "Stdin is empty."

This approach allows developers to check for data in stdin without blocking and proceed with their program's logic accordingly. It is particularly useful when working with pipelines or handling user input from stdin.

The above is the detailed content of How to Check for Data in Stdin without Blocking in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template