[Haskell-beginners] how to read file with locking

Joey Hess joey at kitenet.net
Sat Oct 9 18:49:12 EDT 2010


The function below always returns "", rather than the file's contents.
_Real World Haskell_ touches on how laziness can make this problimatic,
without really giving a solution, other than throwing in a putStr to
force evaluation, which can't be done here. How can I make  hGetContents
strict, to ensure the file contents are really read before it gets closed?

readFile' file = do
        f <- openFile file ReadMode
	-- locking will go here
        s <- hGetContents f
        hClose f
        return s

Also, I noticed that opening a file and locking it involves a
very verbose seeming dance. (It's 2 lines of code in most other languages.)
Does this indicate that few people bother with file locking in Haskell
and so it still has these rough edges, or that there's a better way to do
it that I have not found yet?

openLocked file = do
        handle <- openFile file ReadMode
        lockfd <- handleToFd handle -- closes handle
        waitToSetLock lockfd (ReadLock, AbsoluteSeek, 0, 0)
        handle' <- fdToHandle lockfd
        return handle'

-- 
see shy jo
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 828 bytes
Desc: Digital signature
Url : http://www.haskell.org/pipermail/beginners/attachments/20101009/5eebe19e/attachment.bin


More information about the Beginners mailing list