Skip to content

Commit

Permalink
Enable CLOEXEC on the open file descriptor
Browse files Browse the repository at this point in the history
This prevents child processes from inheriting an open file lock, which
can cause locking mechanisms to misbehave in serious ways. Ideally, we
would open the file descriptor with CLOEXEC enabled, but since unix 2.8
hasn't been released yet and we want backwards compatibility with older
releases, this commit sets CLOEXEC after opening the file descriptor.
This may seem like a race condition at first. However, since the lock is
always taken after CLOEXEC is set, the worst that can happen is that a
child process inherits the open FD in an _unlocked_ state. While
non-ideal from a performance standpoint, it doesn't introduce any
locking bugs.
  • Loading branch information
snoyberg committed Apr 30, 2019
1 parent d5b510a commit 4f08049
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions System/FileLock/Internal/Flock.hsc
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import Data.Bits
import Foreign.C.Error
import Foreign.C.Types
import System.Posix.Files
import System.Posix.IO (openFd, closeFd, defaultFileFlags, OpenMode(..))
import System.Posix.IO (openFd, closeFd, defaultFileFlags, OpenMode(..), setFdOption, FdOption(..))
import System.Posix.Types
import Prelude

Expand All @@ -38,7 +38,10 @@ unlock :: Lock -> IO ()
unlock fd = closeFd fd

open :: FilePath -> IO Fd
open path = openFd path WriteOnly (Just stdFileMode) defaultFileFlags
open path = do
fd <- openFd path WriteOnly (Just stdFileMode) defaultFileFlags
setFdOption fd CloseOnExec True
return fd

flock :: Fd -> Bool -> Bool -> IO Bool
flock (Fd fd) exclusive block = do
Expand Down

0 comments on commit 4f08049

Please sign in to comment.