Curious situation with unlink() and open()

Lennart Sorensen lsorense-1wCw9BSqJbv44Nm34jS7GywD8/FfD2ys at public.gmane.org
Mon Apr 30 16:15:33 UTC 2012


On Mon, Apr 30, 2012 at 12:59:15AM -0400, William Park wrote:
> To C experts:
> 
> unlink(2) takes path[] instead of 'fd'.  How do people deal with the
> following situation?
>     1. Same file is open()ed in 2 different processes (same program, but
>     different instances), so that you have fd1 and fd2.
> 
>     2. Both fd1 and fd2 try for write-lock.  Since fd1 started first, it
>     gets the write-lock, while fd2 waits until fd1 is closed.  That's
>     fine.
> 
>     3. You do some I/O with fd1.  Then, you unlink() the original file,
>     and close(fd1).  Even though the file may be gone from sight, fd2 is
>     still active, so inode2 is still there.
> 
>     4. Now that fd1 is closed, fd2 gets the write-lock.  You do some I/O
>     with fd2, and close(fd2).
> 
>     5. Since all reference to the original file is gone, the file is
>     permanantly gone, along with all I/O done with fd2.  Bummer!
> 
> How do you keep what you did with fd2?

Don't unlink the file if you don't want it gone.

If you open the same inode twice, and then unlink it, anything you write
to that inode still goes to the inode, since unlink does not take effect
until all open handles to the inode are gone and no more directories
link to it.

So in your case you have two open handles, and one directory entry.
You close one handle, unlink the directory entry and then close the
other handle.  It is now gone as it should be.

If you want to be able to have handle two create a new file with the
same name after whoever had handle one unlinked it, well then that's
a very different problem and means you have to prevent handle two even
opening the file while handle one is using it.

It is doing exactly what you asked for.

And this is not a C issue, this is a unix issue.  I don't think windows
lets you unlink a file while there are open handles to it.

To do what you want you probably have to do some mechanism to make sure
only one part of the program can even have the file open at a time,
so that if one part deletes it, the next part would create a new file
to write to with the same name.

-- 
Len Sorensen
--
The Toronto Linux Users Group.      Meetings: http://gtalug.org/
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://gtalug.org/wiki/Mailing_lists





More information about the Legacy mailing list