|
| 1 | +#if canImport(Darwin) |
| 2 | +import Darwin |
| 3 | +#elseif canImport(Glibc) |
| 4 | +import Glibc |
| 5 | +#elseif canImport(Musl) |
| 6 | +import Musl |
| 7 | +#endif |
| 8 | +import Foundation |
| 9 | + |
| 10 | +enum PosixSpawnFileActionsCloseFrom { |
| 11 | + enum CloseFromError: LocalizedError { |
| 12 | + case descriptorEnumerationFailed(String) |
| 13 | + case actionFailed(Int32) |
| 14 | + |
| 15 | + var errorDescription: String? { |
| 16 | + switch self { |
| 17 | + case let .descriptorEnumerationFailed(details): |
| 18 | + "Could not enumerate /proc/self/fd: \(details)" |
| 19 | + case let .actionFailed(code): |
| 20 | + "Could not configure descriptor cleanup: \(String(cString: strerror(code))) (\(code))" |
| 21 | + } |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + static func descriptorsToClose( |
| 26 | + startingAt minimumFileDescriptor: Int32, |
| 27 | + contentsOfDirectory: (String) throws -> [String] = FileManager.default.contentsOfDirectory(atPath:)) throws |
| 28 | + -> [Int32] |
| 29 | + { |
| 30 | + let entries: [String] |
| 31 | + do { |
| 32 | + entries = try contentsOfDirectory("/proc/self/fd") |
| 33 | + } catch { |
| 34 | + throw CloseFromError.descriptorEnumerationFailed(error.localizedDescription) |
| 35 | + } |
| 36 | + return entries.compactMap(Int32.init) |
| 37 | + .filter { $0 >= minimumFileDescriptor } |
| 38 | + .sorted() |
| 39 | + } |
| 40 | + |
| 41 | + #if canImport(Glibc) || canImport(Musl) |
| 42 | + static func addCloseFrom( |
| 43 | + _ fileActions: inout posix_spawn_file_actions_t, |
| 44 | + startingAt minimumFileDescriptor: Int32) throws |
| 45 | + { |
| 46 | + #if canImport(Glibc) |
| 47 | + try self.check(posix_spawn_file_actions_addclosefrom_np(&fileActions, minimumFileDescriptor)) |
| 48 | + #else |
| 49 | + for descriptor in try self.descriptorsToClose(startingAt: minimumFileDescriptor) { |
| 50 | + try self.check(posix_spawn_file_actions_addclose(&fileActions, descriptor)) |
| 51 | + } |
| 52 | + #endif |
| 53 | + } |
| 54 | + |
| 55 | + private static func check(_ result: Int32) throws { |
| 56 | + guard result == 0 else { |
| 57 | + throw CloseFromError.actionFailed(result) |
| 58 | + } |
| 59 | + } |
| 60 | + #endif |
| 61 | +} |
0 commit comments