gpt4 book ai didi

objective-c - 使用 Grand Central Dispatch 进行文件监控

转载 作者:太空狗 更新时间:2023-10-30 03:31:41 25 4
gpt4 key购买 nike

我正在使用 David Hamrick 的代码示例使用 GCD 监视文件。

int fildes = open("/path/to/config.plist", O_RDONLY);

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE,fildes,
DISPATCH_VNODE_DELETE | DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_ATTRIB | DISPATCH_VNODE_LINK | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE,
queue);
dispatch_source_set_event_handler(source, ^
{
//Reload the config file
});
dispatch_source_set_cancel_handler(source, ^
{
//Handle the cancel
});
dispatch_resume(source);

我想用来监视 plist 的变化。我会在第一次更改后收到通知,但不会收到以下更改的通知。为什么?

最佳答案

您确实可以在收到 DISPATCH_VNODE_DELETE 时重新打开文件并重新注册一个源(删除之前的源)。或者您可以使用专为这种情况设计的调用,即 dispatch_io_create_with_path() - 它不仅会按路径观察,还会为您打开文件并让您异步读取内容。

既然你问了(不确定你问的是哪种技术,但这是最简单的)这里是一个独立的代码示例:

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

int main(int ac, char *av[])
{
int fdes = open("/tmp/pleasewatchthis", O_RDONLY);
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
void (^eventHandler)(void), (^cancelHandler)(void);
unsigned long mask = DISPATCH_VNODE_DELETE | DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND | DISPATCH_VNODE_ATTRIB | DISPATCH_VNODE_LINK | DISPATCH_VNODE_RENAME | DISPATCH_VNODE_REVOKE;
__block dispatch_source_t source;

eventHandler = ^{
unsigned long l = dispatch_source_get_data(source);
if (l & DISPATCH_VNODE_DELETE) {
printf("watched file deleted! cancelling source\n");
dispatch_source_cancel(source);
}
else {
// handle the file has data case
printf("watched file has data\n");
}
};
cancelHandler = ^{
int fdes = dispatch_source_get_handle(source);
close(fdes);
// Wait for new file to exist.
while ((fdes = open("/tmp/pleasewatchthis", O_RDONLY)) == -1)
sleep(1);
printf("re-opened target file in cancel handler\n");
source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, fdes, mask, queue);
dispatch_source_set_event_handler(source, eventHandler);
dispatch_source_set_cancel_handler(source, cancelHandler);
dispatch_resume(source);
};

source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE,fdes, mask, queue);
dispatch_source_set_event_handler(source, eventHandler);
dispatch_source_set_cancel_handler(source, cancelHandler);
dispatch_resume(source);
dispatch_main();
}

关于objective-c - 使用 Grand Central Dispatch 进行文件监控,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11355144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com