سؤال

I am learning Mac App development, starting with command line applications and the Core Foundation API. What I am wanting to do is listen for file system events while the application is running in the terminal. When the user quits, it cleanly shuts down the stream and exits. Here is what I have...

#include <CoreServices/CoreServices.h>
#include <stdio.h>

void eventCallback(FSEventStreamRef stream, void *callbackInfo, size_t numEvents, void *paths, FSEventStreamEventFlags flags[], FSEventStreamEventId eventId[]) {
    printf("Test");
}

int main(int argc, const char * argv[])
{
    CFStringRef mypath = CFSTR("/Path/to/folder");
    CFArrayRef paths = CFArrayCreate(NULL, (const void **)&mypath, 1, NULL);

    CFRunLoopRef loop = CFRunLoopGetMain();
    FSEventStreamRef stream = FSEventStreamCreate(NULL, eventCallback, NULL, paths, kFSEventStreamEventIdSinceNow, 3.0, kFSEventStreamCreateFlagNone);
    FSEventStreamScheduleWithRunLoop(stream, loop, kCFRunLoopDefaultMode);
    FSEventStreamStart(stream);
    bool done;

    # Somehow put main thread to sleep here...

    # On exit of application
    FSEventStreamStop(stream);
    FSEventStreamInvalidate(stream);
    FSEventStreamRelease(stream);

    return 0;
}

So I've determined that using either the main threads run loop (or maybe a separate thread) should do this work, but I am not sure the best way in which to put the thread to sleep while waiting for events. I am not familiar enough with Apple's API to know what to do.

Thanks for any help!

هل كانت مفيدة؟

المحلول

# Somehow put main thread to sleep here…
CFRunLoopRun();

There you go.

CFRunLoopRun() spins the run loop for the current thread (in this case, the main thread). Since you’ve attached an FS event stream to the main run loop, your FS events will be processed by this run loop and, consequently, your callback function will be called. The run loop will keep spinning until you call CFRunLoopStop() (if you call it).

You need to decide how to handle program termination, though. Cocoa applications can use the convenient -[NSApplicationDelete willTerminate:] method to perform cleanup operations. Since you are not using Cocoa, you’ll have to roll your own, maybe by using atexit(3) or signal(3) and using ⌃C to quit the program.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top