保存文件后文件监视器停止

时间:2011-08-17 15:20:55

标签: cocoa monitoring kqueue file-monitoring

我正在尝试使用kqueue通过名为UKKQueue的包装器here来监控单个文件的版本。这个包装器非常简单,这是我正在使用的测试代码:

@implementation FileMonitorTestAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    fileWatcher = [[UKKQueue alloc] init];
    [fileWatcher addPath:@"/Users/bruno/Desktop/SyncTestLog"];
    [fileWatcher setDelegate:self];
}

- (void)dealloc {
    [fileWatcher release];
}

-(void) watcher: (id<UKFileWatcher>)kq receivedNotification: (NSString*)nm forPath: (NSString*)fpath {
    NSLog(@"UKFileWatcher: %@ - notification: %@ - filePath: %@", kq, nm, fpath);
}

@end

/Users/bruno/Desktop/SyncTestLog处的文件是纯文本文件。当我使用终端中的nano编辑它时,输出显示为预期:

2011-08-17 11:46:27.316 FileMonitorTest[1235:707] UKFileWatcher: <UKKQueue: 0x100117da0> - notification: UKKQueueFileWrittenToNotification - filePath: /Users/bruno/Desktop/SyncTestLog
2011-08-17 11:46:27.317 FileMonitorTest[1235:707] UKFileWatcher: <UKKQueue: 0x100117da0> - notification: UKKQueueFileSizeIncreasedNotification - filePath: /Users/bruno/Desktop/SyncTestLog
2011-08-17 11:46:27.751 FileMonitorTest[1235:707] UKFileWatcher: <UKKQueue: 0x100117da0> - notification: UKKQueueFileAttributesChangedNotification - filePath: /Users/bruno/Desktop/SyncTestLog

现在,当我使用TextEdit或TextWrangler编辑它时,监控停止报告在我第一次保存文件后发生了变化。 Heres是最后报道的事件:

2011-08-17 10:57:45.792 FileMonitorTest[897:707] UKFileWatcher: <UKKQueue: 0x10035ae10> - notification: UKKQueueFileAttributesChangedNotification - filePath: /Users/bruno/Desktop/SyncTestLog
2011-08-17 10:57:46.463 FileMonitorTest[897:707] UKFileWatcher: <UKKQueue: 0x10035ae10> - notification: UKKQueueFileAttributesChangedNotification - filePath: /Users/bruno/Desktop/SyncTestLog
2011-08-17 10:57:54.043 FileMonitorTest[897:707] UKFileWatcher: <UKKQueue: 0x10035ae10> - notification: UKKQueueFileDeletedNotification - filePath: /Users/bruno/Desktop/SyncTestLog

据我所知,UKKQueue使用标记O_EVTONLY获取了一个类似于unix的文件描述符open()。出于某种原因,TextEdit(和TextWrangler)在保存文件时会生成此UKKQueueFileDeletedNotification通知。

我需要的是“永远”继续监听文件中的更改。我想我可以在UKKQueueFileDeletedNotification到来时重新创建显示器,但我正在寻找更干净的东西。

由于

编辑: 我刚刚在Google Toolbox For Mac中找到了一个名为GTMFileSystemKQueue的类来解决我的问题。我的问题仍然没有答案。

2 个答案:

答案 0 :(得分:3)

我在现代Objective-C中重写了UKKQueue。新课程的工作方式相同,只是更好,更快,更简洁。它还修复了本文中描述的错误以及其他几个错误。

您可以在此处找到新课程VDKQueue:http://github.com/bdkjones/VDKQueue

答案 1 :(得分:1)

这里的问题是TextEdit和TextWrangler正在使用不直接写入文件的安全保存(或...atomically:YES),但首先写入临时文件,然后重命名文件以替换原始路径保存在临时位置的文件。

这样做的结果是你的kqueue将监视原来的文件,该文件将被安全保存机制删除。

GTMFileSystemKQueueacrossReplace参数而起作用,该参数监视删除/重命名操作并将kqueue重新注册到原始路径。快速检查UKKQueue和VDKQueue似乎表明这两者都没有。