gpt4 book ai didi

python - 进程退出后需要刷新文件吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:56:38 26 4
gpt4 key购买 nike

我正在使用 openwrite(即直接内核调用)从一个进程写入文件。写入后,我只需简单地close并在不刷新的情况下退出应用程序。现在,应用程序从 Python-Wrapper 启动,它在应用程序退出后立即读取文件。然而,有时 Python 包装器会读取不正确的数据,就好像我仍在读取文件的旧版本(即包装器读取过时数据)

我认为无论文件元数据和内容是否写入磁盘,用户可见的内容始终有效且一致(即缓冲区至少刷新到内存,因此后续读取获得相同的内容,即使它可能不会提交到磁盘。)这是怎么回事?我需要在我的应用程序中关闭时同步吗?或者我是否可以在从 Python 脚本运行我的应用程序后简单地发出一个 sync 命令以保证所有内容都已正确写入?这是在 ext4 上运行。

在 Python 方面:

# Called for lots of files
o = subprocess.check_output (['./App.BitPacker', inputFile]) # Writes indices.bin and dict.bin
indices = open ('indices.bin', 'rb').read ()
dictionary = open ('dict.bin', 'rb').read ()

with open ('output-file', 'wb') as output:
output.write (dictionary) # Invalid content in output-file ...
# output-file is a placeholder, one output-file per inputFile or course

最佳答案

我从来没有遇到过你的问题,并且总是发现调用 close() 就足够了。但是,从 close(2) 上的 man 条目:

A successful close does not guarantee that the data has been successfully saved to disk, as the kernel defers writes. It is not common for a file system to flush the buffers when the stream is closed. If you need to be sure that the data is physically stored use fsync(2). (It will depend on the disk hardware at this point.)

因为在撰写本文时,您还没有包含写入过程的代码,我只能建议在该过程中添加对 fsync 的调用,看看这是否会产生影响。

关于python - 进程退出后需要刷新文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25382434/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com