如何在OS X上监视文件更改? [英] How do I watch for file changes on OS X?

查看:105
本文介绍了如何在OS X上监视文件更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望收到有关写入给定文件的通知-无需轮询,无需读取文件,也不必监视父目录并观看文件修改时间戳.我该怎么办?

I would like to be notified of writes into a given file – without polling, without having to read from the file and without having to monitor the parent directory and watch the file modification time stamps. How do I do that?

推荐答案

我找不到一个简单的示例,所以我正在贡献我想出的东西以供将来参考:

I couldn’t find a simple example, so I’m contributing what I came up with for future reference:

@interface FileWatch ()
@property(assign) dispatch_source_t source;
@end

@implementation FileWatch
@synthesize source;

- (id) initWithPath: (NSString*) path targetQueue: (dispatch_queue_t) queue block: (dispatch_block_t) handler
{
    self = [super init];

    int descriptor = open([path fileSystemRepresentation], O_EVTONLY);
    if (descriptor < 0) {
        return nil;
    }

    [self setSource:dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, descriptor, DISPATCH_VNODE_WRITE, queue)];
    dispatch_source_set_event_handler(source, handler);
    dispatch_source_set_cancel_handler(source, ^{
        close(descriptor);
    });

    dispatch_resume(source);
    return self;
}

- (void) dealloc
{
    if (source) {
        dispatch_source_cancel(source);
        dispatch_release(source);
        source = NULL;
    }
}

@end

这篇关于如何在OS X上监视文件更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆