10

是否有一个haskell 库函数可以在不轮询的情况下监控文件?

通过轮询,我会做这样的事情:

monitor file mtime handler = do
    threadDelay n -- sleep `n` ns
    t <- getModificationTime file
    if t > mtime
        then handler >> monitor file t handler
        else monitor file mtime handler

我想要的是一个阻塞的 getModificationTime ,它将被系统唤醒。有什么可用的吗?

如果它仅可用于 posix 系统,我会非常高兴,但越便携越好 :-)

编辑:我知道hinotify,但我在 Mac 上(这就是我提到 POSIX 的原因)。

4

3 回答 3

10

kqueue 包应该这样做:http://hackage.haskell.org/package/kqueue

于 2012-11-30T10:35:04.623 回答
7

有一个 GSoC 项目导致使用系统特定库的fsnotify包,并回退到轮询。它在 Mac 上使用hfsevents

于 2012-12-01T17:12:25.777 回答
5

Sjoerd Visscher 建议的软件包就像一个魅力(使用 GHC 7.0.3 和 kqueue 0.1.2.4,Mac OS X 10.6 Snow Leopard)。

我使用它编译了一个快速示例(因为我找不到 API 文档,但在 github 上有一些示例):

import Control.Concurrent.MVar
import System.KQueue.HighLevel (watchFile, EventType, Watcher)
import System.Environment (getArgs)

watch :: MVar EventType -> FilePath -> IO Watcher
watch chan file =
    let handler ev = putMVar chan ev
    in  watchFile file handler

listen :: MVar EventType -> IO ()
listen chan = takeMVar chan >>= print >> listen chan

main :: IO ()
main = do
        args <- getArgs
        chan <- newEmptyMVar
        mapM (watch chan) args
        listen chan

这将创建一个小程序,您可以将文件路径作为参数传递并监视这些文件。事件通过主线程反馈MVar并由主线程读取,主线程基本上是由listen. 该程序必须被杀死,^C因为它被设计为永远运行。

于 2012-11-30T22:05:52.947 回答