在无限循环过程中删除打开的文件

发布于 2024-09-06 15:01:27 字数 130 浏览 5 评论 0原文

我对以下场景有疑问

场景:

进程或程序首先以写入模式打开文件并进入无限循环,例如: while(1) 其主体具有写入打开的文件的逻辑。

问题:如果我在进程进入无限循环后不久删除打开或创建的文件怎么办

I have doubt in the following scenario

Scenario:

A process or program starts with opening a file in a write mode and entering a infinite loop say example: while(1) whose body has logic to write to the opened file.

Problem: What if i delete the opened or created file soon after the process enters the infinite loop

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

平定天下 2024-09-13 15:01:27

在 Unix 中,用户实际上无法删除文件,他们只能删除对文件的引用。当没有留下任何引用(硬链接和打开的文件描述符)时,内核会删除该文件。

In Unix, users really cannot delete files, they only can drop references to files. The kernel deletes the file when there are no references (hard links and open file descriptors) left.

旧人 2024-09-13 15:01:27

从你所说的来看,听起来实际上你并不想要一个无限循环,而是一个带有一些标志的 while 循环,其效果是

 while (file exists)
     perform operation

From what you're saying, it sounds like in reality you don't want an infinite loop, but rather a while loop with some flag, something to the effect of

 while (file exists)
     perform operation
浅唱ヾ落雨殇 2024-09-13 15:01:27

添加一行,用于在 while 循环期间检查文件是否存在。如果不存在,则终止循环。

Add a line that checks to see if the file exists during the while loop. If it doesn't exist, kill the loop.

楠木可依 2024-09-13 15:01:27

看来发生的事情是你的文件消失了(基本上)。

试试这个,创建一个文件 test.py 并将以下内容放入其中:

import os
f = open('out.txt', 'w') # Open file for writing
f.write("Hi Mom!") # Write something
os.remove('out.txt') # Delete the file
try:
    while True: # Do forever
        f.write("Silly English Kanighit!")
except:
    f.close()

然后 $ python test.py 并按 Enter 键。 Ctrl-C 应该停止执行。由于前面提到的原因,这将打开、删除该文件,然后继续写入不再存在的文件。

但是,如果您确实有不同的问题,例如“如何防止我的文件在写入时被意外删除?”或者其他什么,最好问这个问题。

It appears that what happens is that your file disappears (basically).

Try this, create a file test.py and put the following in it:

import os
f = open('out.txt', 'w') # Open file for writing
f.write("Hi Mom!") # Write something
os.remove('out.txt') # Delete the file
try:
    while True: # Do forever
        f.write("Silly English Kanighit!")
except:
    f.close()

then $ python test.py and hit enter. Ctrl-C should stop the execution. This will open, then delete the file, then continue writing to the file that no longer exists, for the reasons that have previously been mentioned.

However, if you really have a different question such as "How can I prevent my file from being accidentally deleted while I'm writing to it?" or something else, it's probably better to ask that question.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文