I think buf gets a rewrite after each loop iteration. Any suggestions?
Yes, buf will be overwritten every time Read() called.
A file descriptor timeout would be the approach I would use.
s, _ := os.OpenFile("/dev/ttyS0", syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NONBLOCK, 0666) t := syscall.Termios{ Iflag: syscall.IGNPAR, Cflag: syscall.CS8 | syscall.CREAD | syscall.CLOCAL | syscall.B115200, Cc: [32]uint8{syscall.VMIN: 0, syscall.VTIME: uint8(20)}, //2.0s timeout Ispeed: syscall.B115200, Ospeed: syscall.B115200, } // syscall syscall.Syscall6(syscall.SYS_IOCTL, uintptr(s.Fd()), uintptr(syscall.TCSETS), uintptr(unsafe.Pointer(&t)), 0, 0, 0) // Send message n, _ := s.Write([]byte("Test message")) // Receive reply for { buf := make([]byte, 128) n, err = s.Read(buf) if err != nil { // err will equal io.EOF break } fmt.Printf("%v\n", string(buf)) }
Also note: if there is no more data reading and no error, os.File.Read () will return an io.EOF error, as you can see here.
source share