我正在尝试使用XCode(MacOS 10.10)来编码一个小命令行工具,该工具(在MacOS 10.10下)观看了特定的文件夹,并告诉我该文件夹中文件的更改。我正在遵循https://developer.apple.com/library/mac/documentation/darwin/darwin/conceptual/fsevents_progguide/usingthefseventsframework/usisthefseventsframewers.htframework.html
这是我当前的代码:
#import <Foundation/Foundation.h>
#include <CoreServices/CoreServices.h>
void mycallback(
ConstFSEventStreamRef streamRef,
void *clientCallBackInfo,
size_t numEvents,
void *eventPaths,
const FSEventStreamEventFlags eventFlags[],
const FSEventStreamEventId eventIds[])
{
int i;
char **paths = eventPaths;
printf("Callback calledn");
for (i=0; i<numEvents; i++) {
int count;
/* flags are unsigned long, IDs are uint64_t */
printf("Change %llu in %s, flags %lun", eventIds[i], paths[i], eventFlags[i]);
}
}
int main(int argc, const char * argv[]) {
// @autoreleasepool {
// insert code here...
NSLog(@"Starting to watch ");
/* Define variables and create a CFArray object containing
CFString objects containing paths to watch.
*/
CFStringRef mypath = CFSTR("/Users/testuser/");
CFArrayRef pathsToWatch = CFArrayCreate(NULL, (const void **)&mypath, 1, NULL);
void *callbackInfo = NULL; // could put stream-specific data here.
FSEventStreamRef stream;
CFAbsoluteTime latency = 3.0; /* Latency in seconds */
/* Create the stream, passing in a callback */
stream = FSEventStreamCreate(NULL,
&mycallback,
callbackInfo,
pathsToWatch,
kFSEventStreamEventIdSinceNow, /* Or a previous event ID */
latency,
kFSEventStreamCreateFlagNone /* Flags explained in reference */
);
/* Create the stream before calling this. */
FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(),kCFRunLoopDefaultMode);
FSEventStreamStart(stream);
CFRunLoopRun();
return 0;
}
代码编译,可以启动。但是,没有任何事件被解雇。我是Xcode的新手,也从未使用过回调功能。所以我想这是我犯的一个非常愚蠢的错误。
我很感谢任何可能会有所帮助的提示。
预先感谢诺伯特
update :该代码已使用答案中的工作解决方案更新。
根据文档,启动事件流进行发送事件后,您应该致电CFRunLoopRun
。
尝试将while()
循环更改为:
CFRunLoopRun();
更新。我的输出:
$ ./fsevent
2015-05-17 13:51:29.718 fsevent[898:23601] Starting to watch
Callback called
Change 1165579 in /Users/baf/src/tests/, flags 66560
Callback called
Change 1165594 in /Users/baf/src/tests/, flags 66048
看来您有 fseventstreamref流; 评论了。为了开始观看事件,您需要散布该行。看来您的回调打印语句也被评论出来,尽管这似乎只是用于调试。