4

我尝试在文件上使用 kqeue 和 kevent,当我的文件被修改时,我将更新我的软件。当我的文件被删除时,我会删除我软件中的链接。

所以我初始化 kqueue

void myfct(char * path)
{ 
int kq;
int event_fd;
struct kevent events_to_monitor[NUM_EVENT_FDS];
struct kevent event_data[NUM_EVENT_SLOTS];
void *user_data;
struct timespec timeout;
unsigned int vnode_events;

kq = kqueue();

event_fd = open(path, O_EVTONLY);
user_data = path;
timeout.tv_sec = 0;        
timeout.tv_nsec = 500000000;    

vnode_events = NOTE_DELETE |  NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE;
EV_SET( &events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, vnode_events, 0, user_data);

    while (42) 
    {
        int event_count = kevent(kq, events_to_monitor, NUM_EVENT_SLOTS, event_data, num_files, &timeout);

        if (event_count) 
        {
            // Display the right event in event_data[0].fflags
        }
        else 
        {
            NSLog(@"No event.\n");
        }
    }
}

然后当我调用 kevent 并修改我的文件时

我得到了 NOTE_ATTRIB 事件,然后是 NOTE_DELETE ...为什么?

4

1 回答 1

3

As explained by arri in a comment:

Many applications and frameworks don't actually overwrite your file when saving. Instead, they create a new temporary file, write to that, copy the attributes from the old file to the temporary file (which triggers a NOTE_ATTRIB), then rename the temporary file over your old file (which triggers a NOTE_DELETE).

This is called an "atomic save". The advantage is that it's atomic: either the whole save works, or nothing is changed; even if someone unplugs the hard drive unexpectedly at the worst possible time, there is no chance that you end up with a garbled or incomplete file. And, while losing all your changes since the last save might be bad, losing the last 90% of your file is usually even worse.

于 2015-05-02T10:50:25.100 回答