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

Delete file while another process still writes to it

我正在尝试使用 Python:

写入文件
import time

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

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

如果我执行这段代码,而不仅仅是手动删除 "foo.txt" 文件,该过程仍然会在某处写入。

内容会怎样?进程写入文件,但没有文件可用。

实际问题是在写入时更改文件描述符时会发生什么,这是平台特定的。

如果您有一个 POSIX 系统,FD 将保持打开状态直到最后一个消费者关闭它,在这种情况下无法访问内容(文件已经取消链接)。

如果你有一个 windows 系统,我认为你不能在写入文件时删除它(独占访问)。

来自 The Linux Programming Interface 作者:Michael Kerrisk

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.