gpt4 book ai didi

python - 当另一个进程仍在写入时删除文件

转载 作者:行者123 更新时间:2023-11-30 23:15:53 24 4
gpt4 key购买 nike

我正在尝试使用 Python 写入文件:

import time

fo = open("foo.txt", "a+", 1)

while True:
fo.write("Some data to write");
time.sleep(.001)

如果我执行此代码,并且不仅仅是手动删除“foo.txt”文件,该进程仍然会在某处写入。

内容会发生什么情况?该进程写入文件,但没有可用的文件。

最佳答案

来自 Michael Kerrisk 的 Linux 编程接口(interface)

In addition to maintaining a link count for each i-node, the kernel also counts open file descriptions for the file (see Figure 5-2, on page 95). If the last link to a file is removed and any processes hold open descriptors referring to the file, the file won’t actually be deleted until all of the descriptors are closed.

您的脚本已打开该文件,因此它包含一个引用该文件的打开描述符。在您使用 rm 命令删除文件后,系统不会立即删除该文件。但在你的脚本关闭描述符后它会删除它。

我在 man 中找到了引用,来自 man remove:

remove() deletes a name from the filesystem. It calls unlink(2) for files, and rmdir(2) for directories.

If the removed name was the last link to a file and no processes have the file open, the file is deleted and the space it was using is made available for reuse.

If the name was the last link to a file, but any processes still have the file open, the file will remain in existence until the last file descriptor referring to it is closed.

正如 @oglu 在他的回答中提到的,这不是可移植的行为。在 Windows 上,您可以选择是否可以删除已打开的文件。

来自CreateFile function at MSDN

FILE_SHARE_DELETE (0x00000004)

Enables subsequent open operations on a file or device to request delete access.

Otherwise, other processes cannot open the file or device if they request delete access.

If this flag is not specified, but the file or device has been opened for delete access, the function fails.

Note Delete access allows both delete and rename operations.

关于python - 当另一个进程仍在写入时删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28009056/

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