4

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 ?

kavaliero
  • 389
  • 1
  • 4
  • 22
  • have you ever figured this out? I'm getting the same behavior on my mac. I expect the file modification will generate the NOTE_WRITE event but it doesn't. – hopia Aug 03 '12 at 16:49
  • I think the Event on mac is different, when a file is modify, the osx delete the node and recreate it ... it's the only solution in my head but maybe there is another better explication ! – kavaliero Aug 09 '12 at 08:20
  • 2
    i think kavaliero is right. it's what is called an 'atomic save': it created a new file, then removes the old and renames the new file to the original name. this is common practice on (application)framework-level, but not an OSX feature persee. – arri Dec 04 '12 at 17:26

1 Answers1

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.

abarnert
  • 354,177
  • 51
  • 601
  • 671