Problems with Read - Linux /dev/input/event*

1,015 views
Skip to first unread message

Dan Anderson

unread,
Mar 16, 2014, 4:29:26 PM3/16/14
to golan...@googlegroups.com
Trying to read raw evdev events from my keyboard -> /dev/input/event0, using the following code:

func main() {
kbd, _ := os.Open("/dev/input/event0")
defer kbd.Close()

buf := make([]byte, 64)

        n, err := kbd.Read(buf)
//n, err := syscall.Read( int(kbd.Fd()), buf )
fmt.Println(n, err)
}

Which errs. The syscall gives: '-1 invalid argument'. However, the (I assume) corresponding C code works as expected...

#include <fcntl.h>
#include <stdio.h>

int main() {
int fd = open("/dev/input/event0", O_RDONLY);
char buf[64];
        read(fd, buf, sizeof(buf));
printf(buf);

close(fd);
}
 
So, what gives? I'm tempted to write this up as a bug, but this is my first time working with Go syscall, so I'm not confident that I'm not just being stupid. 

Running go1.2 linux/386. 

Dave Cheney

unread,
Mar 16, 2014, 5:32:10 PM3/16/14
to golan...@googlegroups.com
In both samples you have not checked the error from os.Open / open(2)

Péter Szilágyi

unread,
Mar 16, 2014, 5:45:03 PM3/16/14
to Dave Cheney, golang-nuts
Expanding a bit on Dave's suggestions, adding the error check:

func main() {
kbd, err := os.Open("/dev/input/event0")
if err != nil {
panic(err)
}
defer kbd.Close()

buf := make([]byte, 64)

n, err := kbd.Read(buf)
//n, err := syscall.Read( int(kbd.Fd()), buf )
fmt.Println(n, err)
}

and running it now:

  $ go run main.go 
  panic: open /dev/input/event0: permission denied

  goroutine 1 [running]:
  runtime.panic(0x496940, 0xc21001e1b0)
          /opt/google/go/src/pkg/runtime/panic.c:266 +0xb6
  main.main()
          /work/iris/src/github.com/karalabe/test/main.go:11 +0x77
  exit status 2

whoops, /dev/input/event0 requires root permissions (on my Linux at least). Running with sudo:

  $ sudo go run main.go 
  48 <nil>

voila :)

--
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.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages