[Haskell-cafe] Opening the same file multiple times

Donn Cave donn at drizzle.com
Mon Dec 12 12:52:59 EST 2005

Quoth Einar Karttunen <ekarttun at cs.helsinki.fi>:
| *** Exception: z: openFile: resource busy (file is locked)

Now that I have access to a platform where ghc builds, I can
duplicate your results - and in case it helps, here's another
work-around.  Apparently this "feature" uses POSIX filesystem
locks, because it appears that we can exploit the brain-damaged
semantics of that system:  when a process closes a file, all
its locks are cleared - whether they were acquired through that
file descriptor or another unrelated open.  It may be the first
time anyone has ever benefited from this!

import IO

main = do
        fc <- openFile "z" ReadMode   -- sacrificial handle
        fr <- openFile "z" ReadMode
        hClose fc
        fa <- openFile "z" AppendMode
        hPutStr fa "append this line\n"
        hGetLine fr >>= print

If you may need to open more read handles later, you can add
another extra close after the append handle. 

Of course there's a risk that the authors of ghc may notice that
we're doing this and come up with a way to thwart it, but it seems
to me that between interfering with legitimate applications and not
working reliably anyway, there'd be a case for letting go of this
notion altogether.

	Donn Cave, donn at drizzle.com

More information about the Haskell-Cafe mailing list