[Haskell-beginners] Re: how to read file with locking

Jimmy Wylie jwylie at uno.edu
Mon Oct 11 01:30:04 EDT 2010


> I don't know how to build your lockFile function. It seems that it would
> have a side effect of closing the handle. It could return a new handle
> like this, but then withFile's automatic close of the file would be
> defeated.
>
> lockFile h = do
> 	lockfd<- handleToFd h -- closes h
> 	waitToSetLock lockfd (lockType mode, AbsoluteSeek, 0, 0)
> 	newh<- fdToHandle lockfd
> 	return newh
>
> Here's what I'm using instead.
>
> withFileLocked file mode action = do
> 	-- TODO: find a way to use bracket here
>          handle<- openFile file mode
>          lockfd<- handleToFd handle -- closes handle
>          waitToSetLock lockfd (lockType mode, AbsoluteSeek, 0, 0)
>          handle'<- fdToHandle lockfd
>          ret<- action handle'
>          hClose handle'
>          return ret
>                  where
>                          lockType ReadMode = ReadLock
>                          lockType _ = WriteLock
>
I was looking here:
http://www.haskell.org/ghc/docs/6.12.2/html/libraries/unix-2.4.0.1/System-Posix-IO.html

Instead of creating the handle, then converting to an fd, only to return 
a new handle, why don't you start with the file descriptor and convert 
at the end of the process. I don't have time for a full piece of code, 
but maybe something like this:

lockFile file = do
     fd <- openFd ReadOnly Nothing defaultFileFlags
     waitToSetLock fd (lockType mode, AbsoluteSeek, 0, 0)
     handle <- fdToHandle fd
     return handle

You could also use the same sort of code in your withFileLocked function.

> According to strace, this does not involve any system-level locking with
> flock/fcntl/lockf. It is done internally to the ghc process.
>
Thanks for testing that out. I appreciate the information.

Ciao,
Jimmy



More information about the Beginners mailing list