是否有一个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的原因)。
答案 0 :(得分:10)
kqueue包应该这样做:http://hackage.haskell.org/package/kqueue
答案 1 :(得分:7)
答案 2 :(得分: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
终止,因为它旨在永远运行。