scr*_*avy 10 haskell polling inotify busy-waiting
是否有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
Run Code Online (Sandbox Code Playgroud)
我想要的是一个阻塞的getModificationTime,它将被系统唤醒.有什么东西可用吗?
如果只有posix系统可用,我会非常高兴,但越便携越好:-)
编辑:我知道 hinotify,但我在Mac上(这就是为什么我提到POSIX).
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
Run Code Online (Sandbox Code Playgroud)
这将创建一个小程序,您可以将文件路径作为参数传递并监视这些文件.事件通过MVar
主线程反馈并由主线程读取,这主要是由实现的循环listen
.程序必须被杀死,^C
因为它被设计为永远运行.