views:

60

answers:

4

Hi ,

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

Thanks in advance........

A: 

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

jbudge
+4  A: 

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.

ninjalj
Thanks for your response what if deleted as root user
Fedrick
root is just a user. Only the kernel knows when a file can be deleted.
ninjalj
+1  A: 

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
AndyPerfect
I don't think that's applicable to the question - the question was: what if I open a file, enter write mode, THEN enter an infinite loop. Thus, once the loop has been entered, I'm assuming that the file does indeed exist because it was just opened beforehand. Nowhere in the question was it stated that reopening and closing would be done in the loop, so I don't believe that would be an issue.
AndyPerfect
Sure it exists, but it won't have the link (filename) that was "deleted" (unlinked, really), though on Linux you'll still be able to access it via /proc/<pid>/fd/<fd>
ninjalj
Excellent , thanks for all your responses
Fedrick
A: 

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.

Wayne Werner
Of coarse it only "disappears" if it isn't that big in size. Try deleting a multi-gigabyte file that's still being referenced. It's quite noticeable the file is still there, only the filename has really disappeared.
ninjalj
Of course. And if you really want to get technical once you've deleted the file (unless you've done one of those fancy schmancy overwrites) it's still there too ;)
Wayne Werner