Watching for filename changes (via Dispatch Sources)

an example that monitors a file for name changes and performs some custom behavior whenit does. (You would provide the actual behavior in place of the MyUpdateFileName function called in theexample.) Because a descriptor is opened specifically for the dispatch source, the dispatch source includes acancellation handler that closes the descriptor. Because the file descriptor created by the example is associatedwith the underlying file-system object, this same dispatch source can be used to detect any number of filename changes


dispatch_source_t MonitorNameChangesToFile(const char* filename)
  {
     int fd = open(filename, O_EVTONLY);
     if (fd == -1)
return NULL;
dispatch_queue_t queue =
  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE,
                  fd, DISPATCH_VNODE_RENAME, queue);
if (source) {
        // Copy the filename for later use.
        int length = strlen(filename);
        char* newString = (char*)malloc(length + 1);
        newString = strcpy(newString, filename);
        dispatch_set_context(source, newString);
        // Install the event handler to process the name change
        dispatch_source_set_event_handler(source, ^{
              const char*  oldFilename = (char*)dispatch_get_context(source);
              MyUpdateFileName(oldFilename, fd);
        });
        // Install a cancellation handler to free the descriptor
        // and the stored string.
        dispatch_source_set_cancel_handler(source, ^{
            char* fileStr = (char*)dispatch_get_context(source);
            free(fileStr);
            close(fd);
});
        // Start processing events.
   dispatch_resume(source);
}
   else
      close(fd);
   return source;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值