git-annex/Utility/OpenFile.hs
Joey Hess 033e4b086f
audit all openFd and dupping for close-on-exec
Made all uses of openFd and dup set the close-on-exec flag, with a few
exceptions when starting a git-annex daemon.

Made openFdWithMode be used everywhere, rather than openFd.
Adding a new parameter to it ensures I checked everything.
And will help to make sure this gets considered in the future when
opening fds.

In lockPidFile, the only thing that keeps the pid file locked, once
daemonize re-runs the command in a new session, is that the fd is
inherited.

In Utility.LogFile.redir, the new fd it dups to does not have the
close-on-exec flag set, because this is used to set up the stdout and
stderr fds, which need to be inherited by child processes.

Same in Assistant.startDaemon where the browser gets started with the
original stdout and stderr.

This does nothing about uses of openFile and similar!

Sponsored-By: mycroft
2025-09-04 16:01:41 -04:00

38 lines
1 KiB
Haskell

{- Opening files
-
- Copyright 2024 Joey Hess <id@joeyh.name>
-
- License: BSD-2-clause
-}
{-# LANGUAGE CPP #-}
module Utility.OpenFile where
#ifndef mingw32_HOST_OS
import System.IO
import System.Posix.IO
import GHC.IO.FD
import GHC.IO.Handle.FD
import GHC.IO.Device
import Utility.OpenFd
import Utility.RawFilePath
import Utility.FileSystemEncoding
{- Usually, opening a Handle to a file that another thread also has open
- for write is prevented, which avoids a lot of concurrency bugs especially
- with lazy IO.
-
- However, sometimes one thread is writing and another thread really wants
- to read from the same file. This bypasses the usual locking, by claiming
- that an opened FD is a Stream.
-}
openFileBeingWritten :: RawFilePath -> IO Handle
openFileBeingWritten f = do
fd <- openFdWithMode f ReadOnly Nothing defaultFileFlags (CloseOnExecFlag True)
(fd', fdtype) <- mkFD (fromIntegral fd) ReadMode (Just (Stream, 0, 0)) False False
mkHandleFromFD fd' fdtype (fromRawFilePath f) ReadMode False Nothing
#endif