question about stdin

96 views
Skip to first unread message

Денис Мухортов

unread,
Dec 12, 2021, 11:15:38 AM12/12/21
to golang-nuts
It's a little unclear how os.stdin actually works. Why, if you just run the program, is data from stdin constantly being listened to?
For example:
func main() {
    sc := bufio.NewScanner(os.Stdin)
    for sc.Scan() {
        txt := sc.Text()
        fmt.Printf("echo: %s\n", txt)
    }
} But if you send it to stdin ahead of time, the loop will run once and the program will exit(echo smth | go run main.go)

Axel Wagner

unread,
Dec 12, 2021, 11:34:27 AM12/12/21
to golang-nuts
os.Stdin is whatever the file descriptor 0 is being connected to by the OS. Depending on the type of file descriptor, Read will behave differently. If you call a program on the command line, the shell connects it to its controlling terminal, which is usually line-buffered and a read from it will block until a new line is written. If you pipe another command into it, it will connect that program's stdout to your programs stdin and as soon as that program (echo, in your example) finishes, a Read will return io.EOF.

Note that this isn't really Go-specific. All languages will behave that way.


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/268474da-8748-482a-b961-f50fcdbcd68dn%40googlegroups.com.

Jan Mercl

unread,
Dec 12, 2021, 11:42:19 AM12/12/21
to Денис Мухортов, golang-nuts
There's no difference in those two cases, just try to press ctrl-D in
the terminal. IOW, in both cases the loop loops until stdin reports
EOF.

From https://pkg.go.dev/bufio#Scanner

""""
Scanning stops unrecoverably at EOF, the first I/O error, or a token
too large to fit in the buffer.
""""
Reply all
Reply to author
Forward
0 new messages