
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/input.h>
#include <errno.h>

//#define USE_NONBLOCK

char default_name[] = "/dev/input/event2";

int main(int argc, char **argv) {
  struct input_event ev;
  int rc, fd, flags;
  char *filename;

  if(argc > 1)
    filename = argv[1];
  else
    filename = default_name;

  flags = O_RDONLY;
#ifdef USE_NONBLOCK
  flags |= O_NONBLOCK;
#endif
  fd = open(filename, flags);
  if(!fd) {
    printf("error open [%s]: %s\n", filename, strerror(errno));
    exit(1);
  }
  while (1) {
    rc = read(fd, &ev, sizeof(struct input_event));
#ifndef USE_NONBLOCK
    if(rc < 0) {
      printf("error reading: %s\n", strerror(errno));
      break;
    }
#endif
    if(rc >= 0)
      printf("Event: time %ld.%06ld, type %d, code %d, value %d  rc=%d\n",
	     ev.time.tv_sec, ev.time.tv_usec, ev.type,
	     ev.code, ev.value, rc);
#ifdef USE_NONBLOCK
    usleep(100000);
#endif
  }
  close(fd);
  exit(0);
}


