[Haskell-cafe] Opening the same file multiple times

Donn Cave donn at drizzle.com
Mon Dec 12 01:26:48 EST 2005


Quoth Einar Karttunen <ekarttun at cs.helsinki.fi>:
| It seems that opening the same file multiple times (one writer
| and multiple readers) is not supported at least on *nix with
| GHC. I want to use one Handle to use append data till the
| end of the file while other Handles perform random access
| IO with seeks on the file.

How is it not supported?  What happens with something like this

  module Main (main) where
  import IO (openFile, IOMode(..), SeekMode(..), hPutStr, hSeek, hGetLine)
  import System (getArgs)

  main = do
        af <- openFile "z" AppendMode
        sf <- openFile "z" ReadMode
        hPutStr af "append this line\n"
        hSeek sf AbsoluteSeek 40
        hGetLine sf >>= print
        hPutStr af "append this line\n"
        hSeek sf AbsoluteSeek 60
        hGetLine sf >>= print

(It works for me, with hugs on a more or less UNIX-like platform.)

	Donn Cave, donn at drizzle.com

| Sharing the same Handle for all the threads is not possible
| since they perform seeks and may thus mess each other up.
| Hiding the Handle behind a mutex would limit concurrency
| more than I like.
|
| Thus I wanted to open multiple Handles to the file, but
| this seems quite hard. My best guess is to create a function 
| like:
|
| #ifdef mingw32_HOST_OS
| openUnlocked fn mode = openBinaryFile fn mode
| #else
| openUnlocked fn mode = withMVar mutex $ do
|   h  <- openBinaryFile fn mode
|   fd <- handleToFd h
|   unlockFile $ fromIntegral fd
|   return h
|
| {-# NOINLINE mutes #-}
| mutex = unsafePerformIO $ newMVar ()
| #endif
|
| Is there really no simpler solution?


More information about the Haskell-Cafe mailing list