From 070d39b389cabfcbf930a5b4b21cd05ee187e1ad Mon Sep 17 00:00:00 2001 From: sternenseemann <0rpkxez4ksa01gb3typccl0i@systemli.org> Date: Mon, 15 Mar 2021 02:20:37 +0100 Subject: [PATCH] Add socketToFd, a safe-ish Socket destruction method socketToFd invalidates the socket to the rest of the API like close would, but returns the file descriptor instead. This is useful to have if you need an destructor of Socket, but prevents you from continuing to use the Socket even though you are using the file descriptor independently of it. --- src/System/Socket.hsc | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/System/Socket.hsc b/src/System/Socket.hsc index c5f1345..eb2a042 100644 --- a/src/System/Socket.hsc +++ b/src/System/Socket.hsc @@ -60,6 +60,8 @@ module System.Socket ( -- * Operations -- ** socket , socket + -- ** socketToFd + , socketToFd -- ** connect , connect -- ** bind @@ -144,6 +146,7 @@ import GHC.Conc ( closeFdWith ) import Foreign.Storable import Foreign.Marshal.Alloc +import System.Posix.Types (Fd (..)) import System.Socket.Unsafe @@ -455,3 +458,9 @@ getAddress = getAddress' when (i /= 0) (SocketException <$> peek errPtr >>= throwIO) addr <- peek addrPtr return addr + +-- | Invalidate the given 'Socket' and return the file descriptor +-- it held. All calls on the socket will fail after this call. +-- Additionally, the file descriptor needs to be closed manually. +socketToFd :: Socket f t p -> IO Fd +socketToFd (Socket mfd) = Fd . fromIntegral <$> swapMVar mfd (-1)