watch file for changes with kqueue in swift

To watch a file for changes using kqueue in Swift, you can follow the below steps -

  1. Import libc.
main.swift
import libc
12 chars
2 lines
  1. Create a kqueue instance.
main.swift
let queue = kqueue()
21 chars
2 lines
  1. Create a file descriptor using open system call.
main.swift
let fileDescriptor = open("/path/to/file", O_EVTONLY)
54 chars
2 lines
  1. Create an event filter using EVFILT_VNODE constant, which listens for changes in the file.
main.swift
let eventFilter = EVFILT_VNODE
31 chars
2 lines
  1. Create the list of events that you want to monitor. In this case, we are interested in changes to the file and for the file to be deleted. These events are represented by NOTE_DELETE and NOTE_WRITE constants.
main.swift
let eventFlags = UInt16(NOTE_DELETE | NOTE_WRITE)
50 chars
2 lines
  1. Create a new event structure with the file descriptor, filter, flags and fflags set.
main.swift
var event = kevent(ident: UInt(fileDescriptor), filter: Int16(eventFilter), flags: UInt16(EV_ADD | EV_ENABLE | EV_CLEAR), fflags: eventFlags, data: 0, udata: nil)
163 chars
2 lines
  1. Add the created event to the kqueue instance using kevent system call.
main.swift
let result = kevent(queue, &event, 1, nil, 0, nil)
51 chars
2 lines
  1. Now, you can enter into a loop where you can wait for the changes on the file.
main.swift
while true {
    var event = kevent()
    let eventCount = kevent(queue, nil, 0, &event, 1, nil)
    if eventCount > 0 {
        print("File changed")
    }
}
159 chars
8 lines
  1. When you are done watching the file, remove the created event from the kqueue instance.
main.swift
let result = kevent(queue, &event, 1, nil, 0, nil)
51 chars
2 lines

gistlibby LogSnag