xref: /netbsd-src/lib/libc/sys/select.2 (revision 2c64b6b7fb441b0cfe58e59022af25956d69916f)
1.\"	$NetBSD: select.2,v 1.46 2024/09/09 01:20:20 riastradh 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 September 9, 2024
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 returns \-1 and sets
159.Dv errno
160if an error occurred.
161If the time limit expires,
162.Fn select
163returns 0.
164If
165.Fn select
166returns with an error,
167including one due to an interrupted call,
168the descriptor sets will be unmodified.
169.Sh EXAMPLES
170.Bd -literal
171#include <stdio.h>
172#include <stdlib.h>
173#include <unistd.h>
174#include <string.h>
175#include <err.h>
176#include <errno.h>
177#include <sys/types.h>
178#include <sys/time.h>
179
180int
181main(int argc, char **argv)
182{
183	fd_set read_set;
184	struct timeval timeout;
185	int ret, fd, i;
186
187	/* file descriptor 1 is stdout */
188	fd = 1;
189
190	/* Wait for ten seconds. */
191	timeout.tv_sec = 10;
192	timeout.tv_usec = 0;
193
194	/* Initialize the read set to null */
195	FD_ZERO(&read_set);
196
197	/* Add file descriptor 1 to read_set */
198	FD_SET(fd, &read_set);
199
200	/*
201	 * Check if data is ready to be read on
202	 * file descriptor 1, give up after 10 seconds.
203	 */
204	ret = select(fd + 1, &read_set, NULL, NULL, &timeout);
205
206	/*
207	 * Returned value is the number of file
208	 * descriptors ready for I/O, or -1 on error.
209	 */
210	switch (ret) {
211	case \-1:
212		err(EXIT_FAILURE, "select() failed");
213		break;
214
215	case 0:
216		printf("Timeout, no data received.\en");
217		break;
218
219	default:
220		printf("Data received on %d file descriptor(s)\en", ret);
221
222		/*
223		 * select(2) hands back a file descriptor set where
224		 * only descriptors ready for I/O are set. These can
225		 * be tested using FD_ISSET
226		 */
227		for (i = 0; i <= fd; i++) {
228			if (FD_ISSET(i, &read_set)) {
229				printf("Data on file descriptor %d\en", i);
230				/* Remove the file descriptor from the set */
231				FD_CLR(fd, &read_set);
232			}
233		}
234		break;
235	}
236
237	return 0;
238}
239.Ed
240.Sh ERRORS
241An error return from
242.Fn select
243indicates:
244.Bl -tag -width Er
245.It Bq Er EBADF
246One of the descriptor sets specified an invalid descriptor.
247.It Bq Er EFAULT
248One or more of
249.Fa readfds ,
250.Fa writefds ,
251or
252.Fa exceptfds
253points outside the process's allocated address space.
254.It Bq Er EINTR
255A signal was delivered before the time limit expired and
256before any of the selected events occurred.
257.It Bq Er EINVAL
258The specified time limit is invalid.
259One of its components is negative or too large.
260.El
261.Sh SEE ALSO
262.Xr accept 2 ,
263.Xr connect 2 ,
264.Xr gettimeofday 2 ,
265.Xr poll 2 ,
266.Xr read 2 ,
267.Xr recv 2 ,
268.Xr send 2 ,
269.Xr write 2 ,
270.Xr getdtablesize 3
271.Sh STANDARDS
272The
273.Fn select
274function, along with
275.Fn FD_CLR ,
276.Fn FD_ISSET ,
277.Fn FD_SET , and
278.Fn FD_ZERO ,
279conforms to
280.St -xpg4.2 .
281.Pp
282The
283.Fn pselect
284function conforms to
285.St -p1003.1-2004 .
286.Sh HISTORY
287The
288.Fn select
289function call appeared in
290.Bx 4.2 .
291The
292.Fn pselect
293function call first appeared in
294.Nx 3.0 .
295.Sh BUGS
296Although the provision of
297.Xr getdtablesize 3
298was intended to allow user programs to be written independent
299of the kernel limit on the number of open files, the dimension
300of a sufficiently large bit field for select remains a problem.
301The default bit size of
302.Ft fd_set
303is based on the symbol
304.Dv FD_SETSIZE
305(currently 256),
306but that is somewhat smaller than the current kernel limit
307to the number of open files.
308However, in order to accommodate programs which might potentially
309use a larger number of open files with select, it is possible
310to increase this size within a program by providing
311a larger definition of
312.Dv FD_SETSIZE
313before the inclusion of
314.In sys/types.h .
315The kernel will cope, and the userland libraries provided with the
316system are also ready for large numbers of file descriptors.
317.Pp
318Note:
319.Xr rpc 3
320library uses
321.Ft fd_set
322with the default
323.Dv FD_SETSIZE
324as part of its ABI.
325Therefore, programs that use
326.Xr rpc 3
327routines cannot change
328.Dv FD_SETSIZE .
329.Pp
330Alternatively, to be really safe, it is possible to allocate
331.Ft fd_set
332bit-arrays dynamically.
333The idea is to permit a program to work properly even if it is
334.Xr execve 2 Ns 'd
335with 4000 file descriptors pre-allocated.
336The following illustrates the technique which is used by
337userland libraries:
338.Pp
339.Bd -literal -offset indent -compact
340	fd_set *fdsr;
341	int max = fd;
342
343	fdsr = (fd_set *)calloc(howmany(max+1, NFDBITS),
344	    sizeof(fd_mask));
345	if (fdsr == NULL) {
346		...
347		return (-1);
348	}
349	FD_SET(fd, fdsr);
350	n = select(max+1, fdsr, NULL, NULL, &tv);
351	...
352	free(fdsr);
353.Ed
354.Pp
355.Fn select
356should probably have been designed to return the time remaining from the
357original timeout, if any, by modifying the time value in place.
358Even though some systems stupidly act in this different way, it is
359unlikely this semantic will ever be commonly implemented, as the
360change causes massive source code compatibility problems.
361Furthermore, recent new standards have dictated the current behaviour.
362In general, due to the existence of those
363non-conforming systems, it is unwise to assume that the timeout
364value will be unmodified by the
365.Fn select
366call, and the caller should reinitialize it on each invocation.
367Calculating the delta is easily done by calling
368.Xr gettimeofday 2
369before and after the call to
370.Fn select ,
371and using
372.Fn timersub
373(as described in
374.Xr getitimer 2 ) .
375.Pp
376Internally to the kernel,
377.Fn select
378works poorly if multiple processes wait on the same file descriptor.
379