go – Reading from stdin in golang-ThrowExceptions

Exception or error:

I’m trying to read from Stdin in Golang as I’m trying to implement a driver for Erlang. I have the following code:

package main

import (
    "fmt"
    "os"
    "bufio"
    "time"
)

func main() {
    go func() { 
        stdout := bufio.NewWriter(os.Stdin) 
        p := []byte{121,100,125,'\n'}
        stdout.Write(p)
        }()
    stdin := bufio.NewReader(os.Stdin)
    values := make([]byte,4,4)
    for{
        fmt.Println("b")
        if read_exact(stdin) > 0 {
            stdin.Read(values)
            fmt.Println("a")
            give_func_write(values)
        }else{
            continue
        }
    }
}




func read_exact(r *bufio.Reader) int {
    bits := make([]byte,3,3)
    a,_ := r.Read(bits)
    if a > 0 {
        r.Reset(r)
        return 1
    }
    return -1
}

func give_func_write(a []byte) bool {
    fmt.Println("Yahu")
    return true
}

However it seems that the give_func_write is never reached. I tried to start a goroutine to write to standard input after 2 seconds to test this.

What am I missing here?
Also the line r.Reset(r). Is this valid in go? What I tried to achieve is simply restart the reading from the beginning of the file. Is there a better way?

EDIT

After having played around I was able to find that the code is stuck at a,_ := r.Read(bits) in the read_exact function

How to solve:

I guess that I will need to have a protocol in which I send a \n to
make the input work and at the same time discard it when reading it

No, you don’t. Stdin is line-buffered only if it’s bound to terminal. You can run your program prog < /dev/zero or cat file | prog.

bufio.NewWriter(os.Stdin).Write(p)

You probably don’t want to write to stdin. See “Writing to stdin and reading from stdout” for details.

Well, it’s not particular clear for me what you’re trying to achieve. I’m assuming, that you just want to read data from stdin by fixed-size chunks. Use io.ReadFull for this. Or if you want to use buffers, you can use Reader.Peek or Scanner to ensure, that specific number of bytes is available. I’ve changed your program to demonstrate the usage of io.ReadFull:

package main

import (
    "fmt"
    "io"
    "time"
)

func main() {
    input, output := io.Pipe()

    go func() {
        defer output.Close()
        for _, m := range []byte("123456") {
            output.Write([]byte{m})
            time.Sleep(time.Second)
        }
    }()

    message := make([]byte, 3)
    _, err := io.ReadFull(input, message)
    for err == nil {
        fmt.Println(string(message))
        _, err = io.ReadFull(input, message)
    }
    if err != io.EOF {
        panic(err)
    }
}

You can easily split it in two programs and test it that way. Just change input to os.Stdin.

Leave a Reply

Your email address will not be published. Required fields are marked *