{-# LINE 1 "GHC/IO/Handle/Lock.hsc" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE InterruptibleFFI #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NoImplicitPrelude #-}
module GHC.IO.Handle.Lock (
FileLockingNotSupported(..)
, LockMode(..)
, hLock
, hTryLock
, hUnlock
) where
{-# LINE 17 "GHC/IO/Handle/Lock.hsc" #-}
import Data.Bits
import Data.Function
import Foreign.C.Error
import Foreign.C.Types
import GHC.IO.Exception
import GHC.IO.FD
import GHC.IO.Handle.FD
{-# LINE 56 "GHC/IO/Handle/Lock.hsc" #-}
import Data.Functor
import GHC.Base
import GHC.Exception
import GHC.IO.Handle.Types
import GHC.Show
data FileLockingNotSupported = FileLockingNotSupported
deriving Show
instance Exception FileLockingNotSupported
data LockMode = SharedLock | ExclusiveLock
hLock :: Handle -> LockMode -> IO ()
hLock :: Handle -> LockMode -> IO ()
hLock h :: Handle
h mode :: LockMode
mode = IO Bool -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (IO Bool -> IO ()) -> IO Bool -> IO ()
forall a b. (a -> b) -> a -> b
$ Handle -> String -> LockMode -> Bool -> IO Bool
lockImpl Handle
h "hLock" LockMode
mode Bool
True
hTryLock :: Handle -> LockMode -> IO Bool
hTryLock :: Handle -> LockMode -> IO Bool
hTryLock h :: Handle
h mode :: LockMode
mode = Handle -> String -> LockMode -> Bool -> IO Bool
lockImpl Handle
h "hTryLock" LockMode
mode Bool
False
hUnlock :: Handle -> IO ()
hUnlock :: Handle -> IO ()
hUnlock = Handle -> IO ()
unlockImpl
{-# LINE 180 "GHC/IO/Handle/Lock.hsc" #-}
lockImpl :: Handle -> String -> LockMode -> Bool -> IO Bool
lockImpl :: Handle -> String -> LockMode -> Bool -> IO Bool
lockImpl h :: Handle
h ctx :: String
ctx mode :: LockMode
mode block :: Bool
block = do
FD{fdFD :: FD -> CInt
fdFD = CInt
fd} <- Handle -> IO FD
handleToFd Handle
h
let flags :: CInt
flags = CInt
cmode CInt -> CInt -> CInt
forall a. Bits a => a -> a -> a
.|. (if Bool
block then 0 else 4)
{-# LINE 185 "GHC/IO/Handle/Lock.hsc" #-}
fix $ \retry -> c_flock fd flags >>= \case
0 -> return True
_ -> getErrno >>= \errno -> if
| not block
, errno == eAGAIN || errno == eACCES -> return False
| errno == eINTR -> retry
| otherwise -> ioException $ errnoToIOError ctx errno (Just h) Nothing
where
cmode :: CInt
cmode = case LockMode
mode of
SharedLock -> 1
{-# LINE 195 "GHC/IO/Handle/Lock.hsc" #-}
ExclusiveLock -> 2
{-# LINE 196 "GHC/IO/Handle/Lock.hsc" #-}
unlockImpl :: Handle -> IO ()
unlockImpl :: Handle -> IO ()
unlockImpl h :: Handle
h = do
FD{fdFD :: FD -> CInt
fdFD = CInt
fd} <- Handle -> IO FD
handleToFd Handle
h
String -> IO CInt -> IO ()
forall a. (Eq a, Num a) => String -> IO a -> IO ()
throwErrnoIfMinus1_ "flock" (IO CInt -> IO ()) -> IO CInt -> IO ()
forall a b. (a -> b) -> a -> b
$ CInt -> CInt -> IO CInt
c_flock CInt
fd 8
{-# LINE 201 "GHC/IO/Handle/Lock.hsc" #-}
foreign import ccall interruptible "flock"
c_flock :: CInt -> CInt -> IO CInt
{-# LINE 267 "GHC/IO/Handle/Lock.hsc" #-}