title: Mac OSX Filesystem modification program. Error: "kevent register: Bad file descriptor"
body: <p>I am writing a program to monitor when files are written to the Mac OSX filesystem using C++. I am calling fsevents directly so that I can get the PID of the process that wrote the file to the filesystem.</p>
  
  <p>When I run the program under my username, I receive an error "kevent register: Bad file descriptor" pertaining to line 43 of my program. If I run it as sudo, the program runs without an error but never receives notifications of files written. I test this out by issuing: <code>echo "blah" &gt;&gt; /tmp/1234</code>.</p>
  
  <p>The code:</p>
  
  <pre><code>#include "fcntl.h"      //for O_RDONLY
  #include "errno.h"      //for errno
  #include "stdio.h"    //for fprintf()
  #include "string.h"     //for strerror()
  #include "stdlib.h"     //for EXIT_SUCCESS
  #include "sys/event.h"  //for kqueue() &amp; more
  #include "unistd.h"     //for close()
  #include &lt;err.h&gt;
  #include &lt;sys/ioctl.h&gt;  //for iotcl control working with fsevents
  
  int main(int argc, char *argv[])
  {
      printf("Exectuted");
  
      struct kevent kev_set;  /* Event we want to monitor */
      struct kevent kev_retr; /* Event triggered */
      int kq, fd, ret;
  
      // directory to monitor, NO checks for errors here
      fd = open ("/dev/fsevents", O_RDONLY);
  
      //if (ioctl(fd, TIOCMGET, &amp;status) &gt;= 0)
      //    err(EXIT_FAILURE, "TIOCMGET failed:");
  
      kq = kqueue();
      if (kq  == -1)
          err(EXIT_FAILURE, "kqueue() failed");
  
      /* Initialize kevent structure. */
          EV_SET(&amp;kev_set, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE, 0, NULL);
  
          /* Attach event to the  kqueue. */
          ret = kevent(kq, &amp;kev_set, 1, NULL, 0, NULL);
          if (ret == -1)
              err(EXIT_FAILURE, "kevent register");
  
      for (;;) {
          /* Sleep until something happens */
          printf("Starting loop\n");
          ret = kevent(kq, NULL, 0, &amp;kev_retr, 1, NULL);
          if (ret == -1)
          {
              err(EXIT_FAILURE, "kevent wait");
          }
          else if (ret &gt; 0) {
                   printf("Something was written: ");
                  }
      }
  
      close(fd);
  
  }
  </code></pre>
  
  <p>The output:</p>
  
  <pre><code>$ ./fsmon-test 
  fsmon-test: kevent register: Bad file descriptor
  </code></pre>
  
  <p>Thank you in advance!</p>