Search code examples
macoseventsnotificationsfilesystemwatcherkernel-extension

how come osx kernel get so many times of file operations


I create a file in userspace(using touch command), I am expecting to see only one OPEN and one CLOSE file operations, however, I get 2 OPEN and 3 CLOSE operations from kernel notification. the operations sequence is like this: open --> close --> open --> close ---> close.... can anybody give me some hints about this? thanks in advance.


Solution

  • Kauth vnode and fileop listeners have been working well for me. If you are receiving event notifications that don't make sense to you, I suggest placing a breakpoint in your kauth listener callback using the kernel debugger and looking at the backtrace. The xnu source code is available, so you should be able to work out from that and the backtrace why you are receiving the notification in question.

    I know that you can get extra close notifications if there are multiple handles to a file. So if you open the file, dup() the file descriptor, then close both handles, you'll get one open and 2 closes. That's just how it is, I'm afraid. There's no public kernel API for determining if a process has a remaining handle on a particular file.

    As for why you are receiving 2 open notifications - it could be to do with the way touch is written, or something to do with the shell. Normally an open notification really does correspond to an open() syscall. If in doubt, write your own "touch" tool that only calls open and close once to test that you're getting the correct events. The source for Apple's touch command is available too if you need it.