Skip to content

Commit 42f3903

Browse files
committed
Duplicate the Handle instead of the fd on Windows
Since getting an fd from a handle transfers ownership, we duplicate the handle before getting an fd from it.
1 parent 95b8e5c commit 42f3903

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

Foundation/FileHandle.swift

+10
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,17 @@ open class FileHandle : NSObject {
111111

112112
// Duplicate the file descriptor.
113113
// Closing the file descriptor while Dispatch is monitoring it leads to undefined behavior; guard against that.
114+
#if os(Windows)
115+
var dupHandle: HANDLE?
116+
if !DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), &dupHandle,
117+
/*dwDesiredAccess:*/0, /*bInheritHandle:*/true, DWORD(DUPLICATE_SAME_ACCESS)) {
118+
fatalError("DuplicateHandleFailed: \(GetLastError())")
119+
}
120+
121+
let fd = _open_osfhandle(intptr_t(bitPattern: dupHandle), 0)
122+
#else
114123
let fd = dup(fileDescriptor)
124+
#endif
115125
let source: DispatchSourceProtocol
116126
if reading {
117127
source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: queue)

0 commit comments

Comments
 (0)