xref: /netbsd-src/lib/libc/sys/select.2 (revision cac8e449158efc7261bebc8657cbb0125a2cfdde)
1.\"	$NetBSD: select.2,v 1.33 2008/05/25 20:13:47 wiz 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.
69This means that
70.Fa nfds
71must be set to the highest file descriptor of the three sets, plus one.
72On return,
73.Fn select
74and
75.Fn pselect
76replace the given descriptor sets
77with subsets consisting of those descriptors that are ready
78for the requested operation.
79.Fn select
80and
81.Fn pselect
82return the total number of ready descriptors in all the sets.
83.Pp
84The descriptor sets are stored as bit fields in arrays of integers.
85The following macros are provided for manipulating such descriptor sets:
86.Fn FD_ZERO fdset
87initializes a descriptor set pointed to by
88.Fa fdset
89to the null set.
90.Fn FD_SET fd fdset
91includes a particular descriptor
92.Fa fd
93in
94.Fa fdset .
95.Fn FD_CLR fd fdset
96removes
97.Fa fd
98from
99.Fa fdset .
100.Fn FD_ISSET fd fdset
101is non-zero if
102.Fa fd
103is a member of
104.Fa fdset ,
105zero otherwise.
106The behavior of these macros is undefined if
107a descriptor value is less than zero or greater than or equal to
108.Dv FD_SETSIZE ,
109which is normally at least equal
110to the maximum number of descriptors supported by the system.
111.Pp
112If
113.Fa timeout
114is a non-null pointer, it specifies a maximum interval to wait for the
115selection to complete.
116If
117.Fa timeout
118is a null pointer, the select blocks indefinitely.
119To affect a poll, the
120.Fa timeout
121argument should be non-null, pointing to a zero-valued timeval or timespec
122structure, as appropriate.
123.Fa timeout
124is not changed by
125.Fn select ,
126and may be reused on subsequent calls; however, it is good style to
127re-initialize it before each invocation of
128.Fn select .
129.Pp
130If
131.Fa sigmask
132is a non-null pointer, then the
133.Fn pselect
134function shall replace the signal mask of the caller by the set of
135signals pointed to by
136.Fa sigmask
137before examining the descriptors, and shall restore the signal mask
138of the calling thread before returning.
139.Pp
140Any of
141.Fa readfds ,
142.Fa writefds ,
143and
144.Fa exceptfds
145may be given as null pointers if no descriptors are of interest.
146.Sh RETURN VALUES
147.Fn select
148returns the number of ready descriptors that are contained in
149the descriptor sets,
150or \-1 if an error occurred.
151If the time limit expires,
152.Fn select
153returns 0.
154If
155.Fn select
156returns with an error,
157including one due to an interrupted call,
158the descriptor sets will be unmodified.
159.Sh EXAMPLES
160.Bd -unfilled
161#include \*[Lt]stdio.h\*[Gt]
162#include \*[Lt]unistd.h\*[Gt]
163#include \*[Lt]string.h\*[Gt]
164#include \*[Lt]err.h\*[Gt]
165#include \*[Lt]errno.h\*[Gt]
166#include \*[Lt]sysexits.h\*[Gt]
167#include \*[Lt]sys/types.h\*[Gt]
168#include \*[Lt]sys/time.h\*[Gt]
169
170int
171main(argc, argv)
172	int argc;
173	char **argv;
174{
175	fd_set read_set;
176	struct timeval timeout;
177	int ret, fd, i;
178
179	/* file descriptor 1 is stdout */
180	fd = 1;
181
182	/* Wait for ten seconds. */
183	timeout.tv_sec = 10;
184	timeout.tv_usec = 0;
185
186	/* Initialize the read set to null */
187	FD_ZERO(\*[Am]read_set);
188
189	/* Add file descriptor 1 to read_set */
190	FD_SET(fd, \*[Am]read_set);
191
192	/*
193	 * Check if data is ready to be readen on
194	 * file descriptor 1, give up after 10 seconds.
195	 */
196	ret = select(fd + 1, \*[Am]read_set, NULL, NULL, \*[Am]timeout);
197
198	/*
199	 * Returned value is the number of file
200	 * descriptors ready for I/O, or -1 on error.
201	 */
202	switch (ret) {
203	case \-1:
204		err(EX_OSERR, "select() failed");
205		break;
206
207	case 0:
208		printf("Timeout, no data received.\\n");
209		break;
210
211	default:
212		printf("Data received on %d file desciptor(s)\\n", ret);
213
214		/*
215		 * select(2) hands back a file descriptor set where
216		 * only descriptors ready for I/O are set. These can
217		 * be tested using FD_ISSET
218		 */
219		for (i = 0; i \*[Lt]= fd; i++) {
220			if (FD_ISSET(i, \*[Am]read_set)) {
221				printf("Data on file descriptor %d\\n", i);
222				/* Remove the file descriptor from the set */
223				FD_CLR(fd, \*[Am]read_set);
224			}
225		}
226		break;
227	}
228
229	return 0;
230}
231.Ed
232.Sh ERRORS
233An error return from
234.Fn select
235indicates:
236.Bl -tag -width Er
237.It Bq Er EBADF
238One of the descriptor sets specified an invalid descriptor.
239.It Bq Er EFAULT
240One or more of
241.Fa readfds ,
242.Fa writefds ,
243or
244.Fa exceptfds
245points outside the process's allocated address space.
246.It Bq Er EINTR
247A signal was delivered before the time limit expired and
248before any of the selected events occurred.
249.It Bq Er EINVAL
250The specified time limit is invalid.
251One of its components is negative or too large.
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