+/* Clean up the CFSocket associated with the file descriptor FD in
+ case the same descriptor is used in other threads later. If no
+ CFSocket is associated with FD, then return 0 without closing FD.
+ Otherwise, return 1 with closing FD. */
+
+int
+mac_try_close_socket (fd)
+ int fd;
+{
+#if SELECT_USE_CFSOCKET
+ if (getpid () == mac_emacs_pid && cfsockets_for_select)
+ {
+ void *key = (void *) fd;
+ CFSocketRef socket =
+ (CFSocketRef) CFDictionaryGetValue (cfsockets_for_select, key);
+
+ if (socket)
+ {
+#if MAC_OS_X_VERSION_MAX_ALLOWED >= 1020
+ CFOptionFlags flags = CFSocketGetSocketFlags (socket);
+
+ if (!(flags & kCFSocketCloseOnInvalidate))
+ CFSocketSetSocketFlags (socket, flags | kCFSocketCloseOnInvalidate);
+#endif
+ BLOCK_INPUT;
+ CFSocketInvalidate (socket);
+ CFDictionaryRemoveValue (cfsockets_for_select, key);
+ UNBLOCK_INPUT;
+
+ return 1;
+ }
+ }
+#endif
+
+ return 0;
+}
+