openTempFile 的原子性
我有以下功能:
safeWrite :: Text -> IO ()
safeWrite c = bracket (openTempFile "/tmp" "list.tmp")
(\(path, h) -> hClose h
>> copyFile path dataFile
>> removeFile path)
(\(_, h) -> TI.hPutStr h c)
我的印象是这样很安全,如果任何时候出现错误都不会发生复制,并且原始文件仍然可以使用。然而就在昨天,我得到了一个空文件,我不知道去哪里查看它。该程序已经运行良好一个多月了,没有出现任何问题,这说明了一些我没有想到的极端情况。
该方法是否保证原子性,这意味着错误在其他地方,或者如果不能,为什么不呢?我应该怎么做才能保证原子性?
I have the following function:
safeWrite :: Text -> IO ()
safeWrite c = bracket (openTempFile "/tmp" "list.tmp")
(\(path, h) -> hClose h
>> copyFile path dataFile
>> removeFile path)
(\(_, h) -> TI.hPutStr h c)
I was under the impression that this would safe, no copying would happen if there were errors during any moment, and the original file would still be usable. However just yesterday I ended up with an empty file, and I have no idea where to go look at it. The program had been running well for over a month without any hiccups which points so some corner case I didn't think of.
Does the method guarantee atomicity, meaning the error is somewhere else, or if not, why not? What should I do to guarantee atomicity?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于 Haskell 异常,您对
mkTemp
的定义是原子的。如果出现异常,它将打印一条有关失败的消息(将文件保留在那里)。您可以做更多的清理工作,可以选择在出现异常时删除文件,或者简单地使用提供的(原子)
mkTemp
函数:openTempFile
:http://hackage.haskell .org/packages/archive/base/4.3.1.0/doc/html/System-IO.html#g:22或使用 posix 层:
Your definition of
mkTemp
is atomic with respect to Haskell exceptions. If there is an exception it will print a message about the failure (leaving the file there).You can do a bit more to clean up, by optionally removing the file if there is an exception, or simply using the provided (atomic)
mkTemp
function:openTempFile
: http://hackage.haskell.org/packages/archive/base/4.3.1.0/doc/html/System-IO.html#g:22or using the posix layer: