@@ -60,6 +60,43 @@ extension CFSocketError {
60
60
}
61
61
#endif
62
62
63
+ #if !canImport(Darwin) && !os(Windows)
64
+ private func findMaximumOpenFromProcSelfFD( ) -> CInt ? {
65
+ guard let dirPtr = opendir ( " /proc/self/fd " ) else {
66
+ return nil
67
+ }
68
+ defer {
69
+ closedir ( dirPtr)
70
+ }
71
+ var highestFDSoFar = CInt ( 0 )
72
+
73
+ while let dirEntPtr = readdir ( dirPtr) {
74
+ var entryName = dirEntPtr. pointee. d_name
75
+ let thisFD = withUnsafeBytes ( of: & entryName) { entryNamePtr -> CInt ? in
76
+ CInt ( String ( decoding: entryNamePtr. prefix ( while: { $0 != 0 } ) , as: Unicode . UTF8. self) )
77
+ }
78
+ highestFDSoFar = max ( thisFD ?? - 1 , highestFDSoFar)
79
+ }
80
+
81
+ return highestFDSoFar
82
+ }
83
+
84
+ func findMaximumOpenFD( ) -> CInt {
85
+ if let maxFD = findMaximumOpenFromProcSelfFD ( ) {
86
+ // the precise method worked, let's return this fd.
87
+ return maxFD
88
+ }
89
+
90
+ // We don't have /proc, let's go with the best estimate.
91
+ #if os(Linux)
92
+ return getdtablesize ( )
93
+ #else
94
+ return 4096
95
+ #endif
96
+ }
97
+ #endif
98
+
99
+
63
100
private func emptyRunLoopCallback( _ context : UnsafeMutableRawPointer ? ) -> Void { }
64
101
65
102
@@ -881,7 +918,7 @@ open class Process: NSObject {
881
918
posix_spawnattr_init ( & spawnAttrs)
882
919
posix_spawnattr_setflags ( & spawnAttrs, . init( POSIX_SPAWN_CLOEXEC_DEFAULT) )
883
920
#else
884
- for fd in 3 ..< getdtablesize ( ) {
921
+ for fd in 3 ... findMaximumOpenFD ( ) {
885
922
guard adddup2 [ fd] == nil &&
886
923
!addclose. contains ( fd) &&
887
924
fd != taskSocketPair [ 1 ] else {
0 commit comments