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