在无限循环过程中删除打开的文件
我对以下场景有疑问
场景:
进程或程序首先以写入模式打开文件并进入无限循环,例如: 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 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.
从你所说的来看,听起来实际上你并不想要一个无限循环,而是一个带有一些标志的 while 循环,其效果是
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 循环期间检查文件是否存在。如果不存在,则终止循环。
Add a line that checks to see if the file exists during the while loop. If it doesn't exist, kill the loop.
看来发生的事情是你的文件消失了(基本上)。
试试这个,创建一个文件 test.py 并将以下内容放入其中:
然后
$ 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:
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.