Deleting an opened file in Infinite looped process
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 enter开发者_如何学编程s the infinite loop
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.
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
Add a line that checks to see if the file exists during the while loop. If it doesn't exist, kill the loop.
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.
精彩评论