Inotify

Version Build Status Platforms Swift Version

一个围绕 Linux inotify API 的 Swift 封装。 旨在尽可能简化在 Swift 中使用 inotify 的过程。

厌倦了 Linux 上 Swift 中缺乏易于 iOS/macOS 上 Swift 访问的 FileSystemEvent 通知吗? 好消息!现在不必为此烦恼了! 通过使用 Linux inotify API,此库为 Swift 带来了对文件通知的一流支持! 轻松地监视文件和目录中的大量事件,并在这些事件被触发时立即执行回调。

特性

安装 (SPM)

将其添加到您的 Package.swift 文件中

.package(url: "https://github.com/Ponyboy47/inotify.git", from: "1.0.2")

用法

InotifyEventDelegate

InotifyEventDelegate 协议指定一个类,该类将在 inotify 事件触发时做出反应。

public protocol InotifyEventDelegate: class {
    func respond(to event: InotifyEvent)
}

您需要某种符合 InotifyEventDelegate 协议的类型才能使用 Inotify。

示例

import Inotify

public final class EventDelegate: InotifyEventDelegate {
    let name: String

    public init(name: String) {
        self.name = name
    }

    public func respond(to event: InotifyEvent) {
        print("\(event.events) events were triggered")
        print("Hello \(name)")
    }
}

Inotify

Inotify 类与 inotify(2) C API 无缝交互,以提供 Swift 风格的高级文件系统事件通知交互。

示例

import Inotify

do {
    // Initializes an inotify instance without any flags
    let inotify = try Inotify()

    // Watch /tmp for files/directories being created, ensuring that /tmp is a
    // directory. Notify the EventDelegate when the event is triggered
    try inotify.watch(path: "/tmp", for: [DirectoryEvent.create], with: [.onlyDirectory], notify: EventDelegate(name: "Ponyboy47"))

    // Synchronously wait for a single event to be triggered
    try inotify.wait()

    // Asynchronously wait for events to be triggered continuously
    inotify.start()

    // Stop waiting for events to be triggered asynchronously
    inotify.stop()

    // No longer watch the specified path for events
    try inotify.unwatch(path: "/tmp")
} catch InotifyError.InitError {
    print("Error initializing the inotify instance: \(error)")
} catch InotifyError.AddWatchError {
    print("Error adding the watcher: \(error)")
} catch InotifyError.UnwatchError {
    print("Error unwatching path: \(error)")
} catch {
    print("Error while waiting for/reading event: \(error)")
}

创建自定义观察者

您可以编写自己的观察者,该观察者将阻塞线程,直到文件描述符准备好进行读取。 默认情况下,我已经提供了一个使用 C select(2) API 的观察者,如果需要,我将在稍后添加其他观察者。(请参阅“待办事项”,了解我计划添加的其他观察者,并随时通过自己制作并提交拉取请求来帮助我)

观察者只需要监视 inotify 文件描述符并阻塞一个线程。 一旦文件描述符准备好读取,就解除对线程的阻塞,Inotify 类对象将处理文件描述符的实际读取,以及后续的 InotifyEvents 创建和回调执行。

您可以查看 EventWatcher.swift,了解我是如何实现基于 select 的观察者的。 阅读 select 手册页(或其他文档)可能有助于您更全面地了解它在后端的作用。

哪个观察者最好?

这实际上取决于您计划如何使用它以及您的项目需要哪些功能。

我实现了基于 select 的观察者,因为我以前曾使用 select 进行 inotify 监视,并且已经熟悉如何使用它。
我对 poll 或 epoll 不是很熟悉,因为我从未使用过它们,但是如果需要非 select 的观察者,那么我将熟悉手册页并自己实现它们。

不过,这些链接包含大量关于 select、poll 和 epoll 的差异、缺点和优势的信息,在决定使用哪个观察者时可能会很有用

已知问题

没有,但是如果您遇到任何问题,请提交问题 :)

待办事项