如果我使用prelude的readfile懒惰地阅读/ proc / pID / stat – 它可以工作但不是我想要的方式.
使用Data.ByteString.readfile切换到严格读取会给我一个空字符串.
我需要严格阅读,以便能够在短时间内比较两次读取的结果.
所以使用System.IO.readfile读取/ proc / pID / stat根本不起作用.它在0.5秒的间隔内给出了相同的结果.我认为这是由于懒惰和半闭手柄或其他东西……
打开和关闭文件句柄显式有效.
h <- openfile "/proc/pID/stat" ReadModest1 <- hGetline h; hClose h
但是,如果我们有字节串严格读取,为什么要做到这一点.对?
这是我被卡住的地方.
import qualifIEd Data.ByteString as BB.readfile "/proc/pID/stat" >>= print
这总是返回一个空字符串.也在GHCI中测试过.
有什么建议.谢谢.
—更新—
感谢DanIEl的建议.
这是我实际需要做的.这可能有助于充分显示我的困境,并提出更多一般性建议.
我需要计算流程统计数据.以下是代码的一部分(仅限cpu使用情况)作为示例.
cpuUsage pID = do st1 <- readProc $"/proc" </> pID </> "stat" threadDelay 500000 -- 0.5 sec st2 <- readProc $"/proc" </> pID </> "stat" let sum1 = (read $words st1 !! 13) + (read $words st1 !! 14) sum2 = (read $words st2 !! 13) + (read $words st2 !! 14) return $round $fromIntegral (sum2 - sum1) * jiffy / delay * 100 where jiffy = 0.01 delay = 0.5 readProc f = do h <- openfile f ReadMode c <- hGetline h hClose h return c
>由于懒惰,Prelude.readfile不起作用
> ByteString的严格函数不起作用.谢谢丹尼尔的解释.
>如果我将整个计算填入其中,那么withfile会工作(它会正确关闭句柄)但是由于计算需要时间,因此间隔不会严格为0.5.
>显式打开和关闭句柄并使用hGetContents不起作用!出于同样的原因,readfile没有.
在这种情况下唯一有效的方法是在上面的代码片段中使用hGetline显式打开和关闭句柄.但这还不够好,因为一些proc文件比/ proc / meminfo更像一行.
所以我需要一个能严格读取整个文件的函数.像hGetContents但严格的东西.
我试图这样做:
readProc f = do h <- openfile f ReadMode c <- hGetContents h let c' = lines c hClose h return c'
希望这些行会触发它完整地读取文件.没运气.仍然得到一个空列表.
任何帮助,建议非常感谢.
解决方法 ByteString代码是readfile :: filePath -> IO ByteStringreadfile f = bracket (openBinaryfile f ReadMode) hClose (\h -> hfileSize h >>= hGet h . fromIntegral)
但是/ proc /不是什么不是真正的文件,它是按需生成的,当你定义它们来获取文件大小时,你得到0.所以ByteString的readfile成功读取0个字节.
总结以上是内存溢出为你收集整理的linux – Haskell:从/ proc读取.严格和懒惰的问题.流程统计全部内容,希望文章能够帮你解决linux – Haskell:从/ proc读取.严格和懒惰的问题.流程统计所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)