我正在尝试调用一个外部进程,该进程写入我通过以下方式获得的临时文件与系统临时文件 https://hackage.haskell.org/package/temporary-1.3/docs/System-IO-Temp.html#v:withSystemTempFile。进程退出后,我可以cat
该文件的内容,但应用程序本身失败openFile: resource busy (file is locked)
尝试读取该文件时出错readFile https://hackage.haskell.org/package/strict-0.3.2/docs/System-IO-Strict.html#v:readFile。我遵循了答案中的建议this https://stackoverflow.com/q/5053135问题并使用了懒惰版本readFile
。这是一个示例代码:
module Main where
import Prelude hiding (readFile)
import System.Process (createProcess, shell)
import System.IO (Handle, hShow)
import System.IO.Temp (withSystemTempFile)
import System.IO.Strict (readFile)
main :: IO ()
main = withSystemTempFile "temp.txt" doSomeStuff
where
doSomeStuff :: FilePath -> Handle -> IO ()
doSomeStuff tempFilePath tempFilePathHandle = do
putStrLn tempFilePath
createProcess $ shell $ "echo \"test\" >> " ++ tempFilePath
getLine -- It's here just to stop program while I check that I can actually "cat" the temp file
-- here I'm able to cat the temp file
contents <- readFile tempFilePath -- here the command fails with /tmp/temp23900-0.txt: openFile: resource busy (file is locked)
putStrLn contents
我仍在了解 Haskell,所以我希望这不是显而易见的事情,因为我已经没有想法了。是什么赋予了?
withSystemTempFile
打开它为您创建的临时文件,因此您无需再次打开它。readFile
获取文件的名称而不是其句柄,因此您知道它一定正在尝试自行打开它。相当于readFile
但对于您已经打开的文件是hGetContents
,因此要解决问题,请替换readFile tempFilePath
with hGetContents tempFilePathHandle
(并更新您的import
因此)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)