Search code examples
gostdin

How Golang implement stdin/stdout/stderr


I did a little program which was able to parse input from command line. It worked well by means of std.in. However, when I looked up the official document for further learning, I found there was too much stuff for me.

var (
   Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
)

I read the document of func NewFile, type uintpty, Package syscall individually but could not figure out the whole. Also, I did not know the meaning of /dev/stdin, either.

I never learned another static programming language except for go. How could I realize the magic of stdin?


Solution

  • From the syscall package, Stdin is just the number 0:

    var (
            Stdin  = 0
            Stdout = 1
            Stderr = 2
    )
    

    This is simply because the posix standard is that stdin is attached to the first file descriptor, 0.

    Since stdin is always present and open by default, os.NewFile can just turn this file descriptor into an os.File, and uses the standard Linux filepath "/dev/stdin" as an easily recognizable file name.