8

I need to create FSEvents watcher for a Folder in Mac. I'm comfortable with C++ and is there a way to get FSEvents notifications in C++ code, rather than Objective-C. Is there some example code to start with and any libraries i need to include ..?

I'm already on this page. http://developer.apple.com/library/mac/#featuredarticles/FileSystemEvents/_index.html

But there seems to be only Objective C, can i have CPP version of it

1 Answer 1

16

Yes, it is possible in C. You should look for Kernel Queues.

Here's a small sample to watch the directory:

#include <errno.h>       // for errno
#include <fcntl.h>       // for O_RDONLY
#include <stdio.h>       // for fprintf()
#include <stdlib.h>      // for EXIT_SUCCESS
#include <string.h>      // for strerror()
#include <sys/event.h>   // for kqueue() etc.
#include <unistd.h>      // for close()

int main (int argc, const char *argv[])
{
   int kq = kqueue ();
   // dir name is in argv[1], NO checks for errors here
   int dirfd = open (argv[1], O_RDONLY);

   struct kevent direvent;
    EV_SET (&direvent, dirfd, EVFILT_VNODE, EV_ADD | EV_CLEAR | EV_ENABLE,
            NOTE_WRITE, 0, (void *)dirname);

   kevent(kq, &direvent, 1, NULL, 0, NULL);

   // Register interest in SIGINT with the queue.  The user data
   // is NULL, which is how we'll differentiate between
   // a directory-modification event and a SIGINT-received event.
   struct kevent sigevent;
   EV_SET (&sigevent, SIGINT, EVFILT_SIGNAL, EV_ADD | EV_ENABLE, 0, 0, NULL);
   // kqueue event handling happens after the legacy API, so make
   // sure it doesn eat the signal before the kqueue can see it.
   signal (SIGINT, SIG_IGN);

   // Register the signal event.
   kevent(kq, &sigevent, 1, NULL, 0, NULL);

   while (1) {
       // camp on kevent() until something interesting happens
       struct kevent change;
       if (kevent(kq, NULL, 0, &change, 1, NULL) == -1) { exit(1); }
       // The signal event has NULL in the user data.  Check for that first.
       if (change.udata == NULL) {
           break;
       } else {
        // udata is non-null, so it's the name of the directory
        printf ("%s\n", (char*)change.udata);
       }
   }
   close (kq);
   return 0;
}

The details can be found in ch. 16 (kqueues and FSEvents) of "Advanced Mac OSX Programming" by Mark Dalrymple. The additional info may be found in *BSD documentation for kqueues.

Or use this API from FSEvents (it's mostly C-based).

FSEventStreamRef FSEventStreamCreate (CFAllocatorRef allocator,
                                  FSEventStreamCallback callback,
                                  FSEventStreamContext *context,
                                  CFArrayRef pathsToWatch,
                                  FSEventStreamEventId sinceWhen,
                                  CFTimeInterval latency,
                                  FSEventStreamCreateFlags flags);

to create the FSEvents event stream with pure-C callback.

Then attach this event stream to your runloop using the

void FSEventStreamScheduleWithRunLoop (FSEventStreamRef streamRef,
                                   CFRunLoopRef runLoop,
                                   CFStringRef runLoopMode);

Yes, here you probably should use a line of Obj-C to get the RunLoop handle: get the CFRunLoop from an NSRunLoop by using -getCFRunLoop

CFRunLoop* loopRef = [[NSRunLoop currentRunLoop] getCFRunLoop];

or use the pure C call

CFRunLoop* loopRef =  CFRunLoopGetCurrent();

Start the event stream with

Boolean FSEventStreamStart (FSEventStreamRef streamRef);

Stop the event stream with

void FSEventStreamStop (FSEventStreamRef streamRef);

And then unschedule it from the runloop with this:

void FSEventStreamUnscheduleFromRunLoop (FSEventStreamRef streamRef,
                                     CFRunLoopRef runLoop,
                                     CFStringRef runLoopMode);

Invalidate the stream (cleanup):

void FSEventStreamInvalidate (FSEventStreamRef streamRef);

Hope this will get you started.

5
  • 1
    In my experiments, kqueue is not functionally equivalent to FSEvents. Thanks for outlining the CFRunLoop bit!
    – berkus
    Jan 7, 2014 at 10:52
  • In your first small sample, it seems like the "dirname" is not defined... ?
    – Sugar
    Jun 1, 2021 at 8:20
  • @Sugar: You are right, the const char* dirname = "some_dir_name" is definitely missing. Actually, it can be just const char* dirname = argv[1]; Jun 1, 2021 at 9:43
  • @ViktorLatypov Thanks, and your sample is really helpful! :)
    – Sugar
    Jun 3, 2021 at 2:53
  • @ViktorLatypov Nice answer :) Can you please tell me how can one compile the code using FSevents (pure C based api) using the g++ compiler? I cannot find which library to link using the -l option :) Thankyou very much :)
    – Aravind A
    Oct 3 at 8:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.