xref: /netbsd-src/lib/libc/sys/select.2 (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1.\"	$NetBSD: select.2,v 1.43 2017/10/25 17:39:47 abhinav Exp $
2.\"
3.\" Copyright (c) 1983, 1991, 1993
4.\"	The Regents of the University of California.  All rights reserved.
5.\"
6.\" Redistribution and use in source and binary forms, with or without
7.\" modification, are permitted provided that the following conditions
8.\" are met:
9.\" 1. Redistributions of source code must retain the above copyright
10.\"    notice, this list of conditions and the following disclaimer.
11.\" 2. Redistributions in binary form must reproduce the above copyright
12.\"    notice, this list of conditions and the following disclaimer in the
13.\"    documentation and/or other materials provided with the distribution.
14.\" 3. Neither the name of the University nor the names of its contributors
15.\"    may be used to endorse or promote products derived from this software
16.\"    without specific prior written permission.
17.\"
18.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21.\" ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28.\" SUCH DAMAGE.
29.\"
30.\"     @(#)select.2	8.2 (Berkeley) 3/25/94
31.\"
32.Dd November 28, 2013
33.Dt SELECT 2
34.Os
35.Sh NAME
36.Nm select ,
37.Nm pselect ,
38.Nm FD_SET ,
39.Nm FD_CLR ,
40.Nm FD_ISSET ,
41.Nm FD_ZERO
42.Nd synchronous I/O multiplexing
43.Sh LIBRARY
44.Lb libc
45.Sh SYNOPSIS
46.In sys/select.h
47.Ft int
48.Fn select "int nfds" "fd_set * restrict readfds" "fd_set * restrict writefds" "fd_set * restrict exceptfds" "struct timeval * restrict timeout"
49.Ft int
50.Fn pselect "int nfds" "fd_set * restrict readfds" "fd_set * restrict writefds" "fd_set * restrict exceptfds" "const struct timespec *restrict timeout" "const sigset_t * restrict sigmask"
51.Fn FD_SET "int fd" "fd_set *fdset"
52.Fn FD_CLR "int fd" "fd_set *fdset"
53.Fn FD_ISSET "int fd" "fd_set *fdset"
54.Fn FD_ZERO "fd_set *fdset"
55.Sh DESCRIPTION
56.Fn select
57and
58.Fn pselect
59examine the I/O descriptor sets whose addresses are passed in
60.Fa readfds ,
61.Fa writefds ,
62and
63.Fa exceptfds
64to see if some of their descriptors
65are ready for reading, are ready for writing, or have an exceptional
66condition pending, respectively.
67The first
68.Fa nfds
69descriptors are checked in each set;
70i.e., the descriptors from 0 through
71.Fa nfds Ns No \-1
72in the descriptor sets are examined.
73This means that
74.Fa nfds
75must be set to the highest file descriptor of the three sets, plus one.
76On return,
77.Fn select
78and
79.Fn pselect
80replace the given descriptor sets
81with subsets consisting of those descriptors that are ready
82for the requested operation.
83.Fn select
84and
85.Fn pselect
86return the total number of ready descriptors in all the sets.
87.Pp
88The descriptor sets are stored as bit fields in arrays of integers.
89The following macros are provided for manipulating such descriptor sets:
90.Fn FD_ZERO fdset
91initializes a descriptor set pointed to by
92.Fa fdset
93to the null set.
94.Fn FD_SET fd fdset
95includes a particular descriptor
96.Fa fd
97in
98.Fa fdset .
99.Fn FD_CLR fd fdset
100removes
101.Fa fd
102from
103.Fa fdset .
104.Fn FD_ISSET fd fdset
105is non-zero if
106.Fa fd
107is a member of
108.Fa fdset ,
109zero otherwise.
110The behavior of these macros is undefined if
111a descriptor value is less than zero or greater than or equal to
112.Dv FD_SETSIZE ,
113which is normally at least equal
114to the maximum number of descriptors supported by the system.
115.Pp
116If
117.Fa timeout
118is a non-null pointer, it specifies a maximum interval to wait for the
119selection to complete.
120If
121.Fa timeout
122is a null pointer, the select blocks indefinitely.
123To poll without blocking, the
124.Fa timeout
125argument should be non-null, pointing to a zero-valued timeval or timespec
126structure, as appropriate.
127.Fa timeout
128is not changed by
129.Fn select ,
130and may be reused on subsequent calls; however, it is good style to
131re-initialize it before each invocation of
132.Fn select .
133.Pp
134If
135.Fa sigmask
136is a non-null pointer, then the
137.Fn pselect
138function shall replace the signal mask of the caller by the set of
139signals pointed to by
140.Fa sigmask
141before examining the descriptors, and shall restore the signal mask
142of the calling thread before returning.
143.Pp
144Any of
145.Fa readfds ,
146.Fa writefds ,
147and
148.Fa exceptfds
149may be given as null pointers if no descriptors are of interest.
150.Sh NOTES
151It is recommended to use the
152.Xr poll 2
153interface instead, which tends to be more portable and efficient.
154.Sh RETURN VALUES
155.Fn select
156returns the number of ready descriptors that are contained in
157the descriptor sets,
158or \-1 if an error occurred.
159If the time limit expires,
160.Fn select
161returns 0.
162If
163.Fn select
164returns with an error,
165including one due to an interrupted call,
166the descriptor sets will be unmodified.
167.Sh EXAMPLES
168.Bd -literal
169#include <stdio.h>
170#include <stdlib.h>
171#include <unistd.h>
172#include <string.h>
173#include <err.h>
174#include <errno.h>
175#include <sys/types.h>
176#include <sys/time.h>
177
178int
179main(int argc, char **argv)
180{
181	fd_set read_set;
182	struct timeval timeout;
183	int ret, fd, i;
184
185	/* file descriptor 1 is stdout */
186	fd = 1;
187
188	/* Wait for ten seconds. */
189	timeout.tv_sec = 10;
190	timeout.tv_usec = 0;
191
192	/* Initialize the read set to null */
193	FD_ZERO(&read_set);
194
195	/* Add file descriptor 1 to read_set */
196	FD_SET(fd, &read_set);
197
198	/*
199	 * Check if data is ready to be read on
200	 * file descriptor 1, give up after 10 seconds.
201	 */
202	ret = select(fd + 1, &read_set, NULL, NULL, &timeout);
203
204	/*
205	 * Returned value is the number of file
206	 * descriptors ready for I/O, or -1 on error.
207	 */
208	switch (ret) {
209	case \-1:
210		err(EXIT_FAILURE, "select() failed");
211		break;
212
213	case 0:
214		printf("Timeout, no data received.\en");
215		break;
216
217	default:
218		printf("Data received on %d file descriptor(s)\en", ret);
219
220		/*
221		 * select(2) hands back a file descriptor set where
222		 * only descriptors ready for I/O are set. These can
223		 * be tested using FD_ISSET
224		 */
225		for (i = 0; i <= fd; i++) {
226			if (FD_ISSET(i, &read_set)) {
227				printf("Data on file descriptor %d\en", i);
228				/* Remove the file descriptor from the set */
229				FD_CLR(fd, &read_set);
230			}
231		}
232		break;
233	}
234
235	return 0;
236}
237.Ed
238.Sh ERRORS
239An error return from
240.Fn select
241indicates:
242.Bl -tag -width Er
243.It Bq Er EBADF
244One of the descriptor sets specified an invalid descriptor.
245.It Bq Er EFAULT
246One or more of
247.Fa readfds ,
248.Fa writefds ,
249or
250.Fa exceptfds
251points outside the process's allocated address space.
252.It Bq Er EINTR
253A signal was delivered before the time limit expired and
254before any of the selected events occurred.
255.It Bq Er EINVAL
256The specified time limit is invalid.
257One of its components is negative or too large.
258.El
259.Sh SEE ALSO
260.Xr accept 2 ,
261.Xr connect 2 ,
262.Xr gettimeofday 2 ,
263.Xr poll 2 ,
264.Xr read 2 ,
265.Xr recv 2 ,
266.Xr send 2 ,
267.Xr write 2 ,
268.Xr getdtablesize 3
269.Sh HISTORY
270The
271.Fn select
272function call appeared in
273.Bx 4.2 .
274.Sh BUGS
275Although the provision of
276.Xr getdtablesize 3
277was intended to allow user programs to be written independent
278of the kernel limit on the number of open files, the dimension
279of a sufficiently large bit field for select remains a problem.
280The default bit size of
281.Ft fd_set
282is based on the symbol
283.Dv FD_SETSIZE
284(currently 256),
285but that is somewhat smaller than the current kernel limit
286to the number of open files.
287However, in order to accommodate programs which might potentially
288use a larger number of open files with select, it is possible
289to increase this size within a program by providing
290a larger definition of
291.Dv FD_SETSIZE
292before the inclusion of
293.In sys/types.h .
294The kernel will cope, and the userland libraries provided with the
295system are also ready for large numbers of file descriptors.
296.Pp
297Note:
298.Xr rpc 3
299library uses
300.Ft fd_set
301with the default
302.Dv FD_SETSIZE
303as part of its ABI.
304Therefore, programs that use
305.Xr rpc 3
306routines cannot change
307.Dv FD_SETSIZE .
308.Pp
309Alternatively, to be really safe, it is possible to allocate
310.Ft fd_set
311bit-arrays dynamically.
312The idea is to permit a program to work properly even if it is
313.Xr execve 2 Ns 'd
314with 4000 file descriptors pre-allocated.
315The following illustrates the technique which is used by
316userland libraries:
317.Pp
318.Bd -literal -offset indent -compact
319	fd_set *fdsr;
320	int max = fd;
321
322	fdsr = (fd_set *)calloc(howmany(max+1, NFDBITS),
323	    sizeof(fd_mask));
324	if (fdsr == NULL) {
325		...
326		return (-1);
327	}
328	FD_SET(fd, fdsr);
329	n = select(max+1, fdsr, NULL, NULL, &tv);
330	...
331	free(fdsr);
332.Ed
333.Pp
334.Fn select
335should probably have been designed to return the time remaining from the
336original timeout, if any, by modifying the time value in place.
337Even though some systems stupidly act in this different way, it is
338unlikely this semantic will ever be commonly implemented, as the
339change causes massive source code compatibility problems.
340Furthermore, recent new standards have dictated the current behaviour.
341In general, due to the existence of those
342non-conforming systems, it is unwise to assume that the timeout
343value will be unmodified by the
344.Fn select
345call, and the caller should reinitialize it on each invocation.
346Calculating the delta is easily done by calling
347.Xr gettimeofday 2
348before and after the call to
349.Fn select ,
350and using
351.Fn timersub
352(as described in
353.Xr getitimer 2 ) .
354.Pp
355Internally to the kernel,
356.Fn select
357works poorly if multiple processes wait on the same file descriptor.
358