27.12.2014 Views

Using TCP Through Sockets

Using TCP Through Sockets

Using TCP Through Sockets

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

select represents sets of file descriptors as bit vectors—one bit per descriptor. The first<br />

bit of a vector is 1 if that set contains file descriptor 0, the second bit is 1 if it contains<br />

descriptor 1, and so on. The argument nfds specifies the number of bits in each of the<br />

bit vectors being passed in. Equivalently, nfds is one more than highest file descriptor<br />

number select must check on.<br />

These file descriptor sets are of type fd set. Several macros in system header files<br />

allow easy manipulation of this type. If fd is an integer containing a file descriptor,<br />

and fds is a variable of type fd set, the following macros can manipulate fds:<br />

– FD_ZERO (&fds);<br />

Clears all bits in a fds.<br />

– FD_SET (fd, &fds);<br />

Sets the bit corresponding to file descriptor fd in fds.<br />

– FD_CLR (fd, &fds);<br />

Clears the bit corresponding to file descriptor fd in fds.<br />

– FD_ISSET (fd, &fds);<br />

Returns a true if and only if the bit for file descriptor fd is set in fds.<br />

select takes three file descriptor sets as input. rfds specifies the set of file descriptors<br />

on which the process would like to perform a read or accept. wfds specifies the set<br />

of file descriptors on which the process would like to perform a write. efds is a set<br />

of file descriptors for which the process is interested in exceptional events such as the<br />

arrival of out of band data. In practice, people rarely use efds. Any of the fd set *<br />

arguments to select can be NULL to indicate an empty set.<br />

The argument timeout specifies the amount of time to wait for a file descriptor to<br />

become ready. It is a pointer to a structure of the following form:<br />

struct timeval {<br />

long tv_sec; /* seconds */<br />

long tv_usec; /* and microseconds */<br />

};<br />

timeout can also be NULL, in which case select will wait indefinitely.<br />

Tips and subtleties<br />

File descriptor limits. Programmers using select may be tempted to write code capable<br />

of using arbitrarily many file descriptors. Be aware that the operating system limits the<br />

number of file descriptors a process can have. If you don’t bound the number of descriptors<br />

your program uses, you must be prepared for system calls like socket and accept to fail with<br />

errors like EMFILE. By default, a modern Unix system typically limits processes to 64 file<br />

17

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!