Python 中的 file.flush() 与 os.fsync()
2016年08月14日 23:28:48 JasonCcccc 阅读数 4562更多
分类专栏: Python
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/End0o0/article/details/52207302
在Python 官方文档https://docs.python.org/2/library/stdtypes.html?highlight=file%20flush#file.flush 关于file.flush() 的说明中写道:“ flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.”flush方法并不强制把数据写入到磁盘文件中,那么flush方法为什么会这样呢?
其实这里有两种层面的buffering:
- Internal buffers
- Operating system buffers
Internal buffers 创建在 runtime/library/language 中避免每次写操作都调用系统call,依次来加速运行。当需要把数据写入文件时,先写入internal buffer, 当internal buffer 溢满时,再调用系统call写入到文件中。
所以为了确保数据写入到了文件中,file.flush() 之后要调用os.fsync()。