1 /* Accept a connection on a socket, with specific opening flags.
2 Copyright (C) 2009 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License along
15 with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
21 #include <sys/socket.h>
25 #include "binary-io.h"
28 # define SOCK_CLOEXEC 0
32 accept4 (int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags)
36 /* Check the supported flags. */
37 if ((flags & ~(SOCK_CLOEXEC | O_TEXT | O_BINARY)) != 0)
43 fd = accept (sockfd, addr, addrlen);
48 # if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
49 /* Native Woe32 API. */
50 if (flags & SOCK_CLOEXEC)
52 HANDLE curr_process = GetCurrentProcess ();
53 HANDLE old_handle = (HANDLE) _get_osfhandle (fd);
57 if (!DuplicateHandle (curr_process, /* SourceProcessHandle */
58 old_handle, /* SourceHandle */
59 curr_process, /* TargetProcessHandle */
60 (PHANDLE) &new_handle, /* TargetHandle */
61 (DWORD) 0, /* DesiredAccess */
62 FALSE, /* InheritHandle */
63 DUPLICATE_SAME_ACCESS)) /* Options */
66 errno = EBADF; /* arbitrary */
70 /* Closing fd before allocating the new fd ensures that the new fd will
71 have the minimum possible value. */
73 nfd = _open_osfhandle ((long) new_handle,
74 O_NOINHERIT | (flags & (O_TEXT | O_BINARY)));
77 CloseHandle (new_handle);
84 if (flags & SOCK_CLOEXEC)
88 if ((fcntl_flags = fcntl (fd, F_GETFD, 0)) < 0
89 || fcntl (fd, F_SETFD, fcntl_flags | FD_CLOEXEC) == -1)
91 int saved_errno = errno;
101 if (flags & O_BINARY)
102 setmode (fd, O_BINARY);
103 else if (flags & O_TEXT)
104 setmode (fd, O_TEXT);