1 /* Non-blocking I/O for pipe or socket descriptors.
2 Copyright (C) 2011-2020 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 3 of the License, or
7 (at your option) any later version.
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
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
20 #include "nonblocking.h"
24 #if defined _WIN32 && ! defined __CYGWIN__
25 /* Native Windows API. */
27 # include <sys/ioctl.h>
28 # include <sys/socket.h>
31 /* Get declarations of the native Windows API functions. */
32 # define WIN32_LEAN_AND_MEAN
35 # if GNULIB_MSVC_NOTHROW
36 # include "msvc-nothrow.h"
41 /* Don't assume that UNICODE is not defined. */
42 # undef GetNamedPipeHandleState
43 # define GetNamedPipeHandleState GetNamedPipeHandleStateA
46 get_nonblocking_flag (int desc
)
48 HANDLE h
= (HANDLE
) _get_osfhandle (desc
);
49 if (h
== INVALID_HANDLE_VALUE
)
54 if (GetFileType (h
) == FILE_TYPE_PIPE
)
56 /* h is a pipe or socket. */
58 if (GetNamedPipeHandleState (h
, &state
, NULL
, NULL
, NULL
, NULL
, 0))
60 return (state
& PIPE_NOWAIT
) != 0;
67 /* The native Windows API does not support non-blocking on regular
73 set_nonblocking_flag (int desc
, bool value
)
75 HANDLE h
= (HANDLE
) _get_osfhandle (desc
);
76 if (h
== INVALID_HANDLE_VALUE
)
81 if (GetFileType (h
) == FILE_TYPE_PIPE
)
83 /* h is a pipe or socket. */
85 if (GetNamedPipeHandleState (h
, &state
, NULL
, NULL
, NULL
, NULL
, 0))
88 if ((state
& PIPE_NOWAIT
) != 0)
92 state
&= ~PIPE_NOWAIT
;
100 if (SetNamedPipeHandleState (h
, &state
, NULL
, NULL
))
109 return ioctl (desc
, FIONBIO
, &v
);
114 /* The native Windows API does not support non-blocking on regular
128 # if GNULIB_defined_O_NONBLOCK
129 # error Please port nonblocking to your platform
132 /* We don't need the gnulib replacement of fcntl() here. */
136 get_nonblocking_flag (int desc
)
140 fcntl_flags
= fcntl (desc
, F_GETFL
, 0);
143 return (fcntl_flags
& O_NONBLOCK
) != 0;
147 set_nonblocking_flag (int desc
, bool value
)
151 fcntl_flags
= fcntl (desc
, F_GETFL
, 0);
154 if (((fcntl_flags
& O_NONBLOCK
) != 0) == value
)
157 fcntl_flags
|= O_NONBLOCK
;
159 fcntl_flags
&= ~O_NONBLOCK
;
160 return fcntl (desc
, F_SETFL
, fcntl_flags
);