kevent NOTE_DELETE is send when I modify my file

601 Views Asked by At

I try to use kqeue and kevent on a file and when my file is modified i will update my software . And when my file is Deleted i delete the link in my software .

So i init 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");
        }
    }
}

then when i call kevent and modify my file

i get the NOTE_ATTRIB event and then the NOTE_DELETE ... why ?

1

There are 1 best solutions below

0
On

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.