flock and sockets

John Hughes rjmh@cs.chalmers.se
Thu, 20 Mar 2003 09:19:10 +0100 (MET)


On Wed, 19 Mar 2003, Simon Marlow wrote:

> > I am planning a Haskell project and I need to access files. Since the
> > program will be automatically started whenever a mail comes
> > in I will need
> > to be able to lock the access to files. Is there any support
> > for this in some library?
>
> Yes, the Posix library distributed with GHC has support for file
> locking.  See
>
>   http://www.haskell.org/ghc/docs/latest/html/hslibs/sec-posix.html
>
> This library is currently undergoing a rewrite - the functionality will
> be available under System.Posix in future releases of GHC (and possibly
> Hugs & NHC).
>

I didn't find this when I needed to lock files, so my solution (under
Unix) was to write a little C code and call it via the FFI. I used a
single lock file, since my application was a CGI script which runs fairly
rarely -- there's no need for a finer grain of locking.

Here's the C code (taken from the web and slightly adapted):

#include <stdio.h>
#include <fcntl.h>

void claimLock()
{
  struct flock fl;
  int fd;

  fl.l_type   = F_WRLCK;  /* F_RDLCK, F_WRLCK, F_UNLCK    */
  fl.l_whence = SEEK_SET; /* SEEK_SET, SEEK_CUR, SEEK_END */
  fl.l_start  = 0;        /* Offset from l_whence         */
  fl.l_len    = 0;        /* length, 0 = to EOF           */
  fl.l_pid    = getpid(); /* our PID                      */

  fd = open("lock", O_WRONLY);

  fcntl(fd, F_SETLKW, &fl);  /* F_GETLK, F_SETLK, F_SETLKW */
}

Here's the corresponding Haskell declaration:

foreign import claimLock :: IO ()

John Hughes