21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

the connections to the server. The increase in file descriptors could be done externally<br />

by using setrlimit( ) before starting the server process (with the bash shell, the<br />

command would be ulimit -n 512).<br />

The proper way to deal with this problem is to allocate the array dynamically and<br />

ensure that FD_SET( ) and FD_CLR( ) resize the array as necessary before modifying it.<br />

Unfortunately, to do this, we need to create a new data type. We define the data type<br />

such that it can be safely cast to an fd_set for passing it directly to select( ):<br />

#include <br />

typedef struct {<br />

long int *fds_bits;<br />

size_t fds_size;<br />

} SPC_FD_SET;<br />

With a new data type defined, we can replace FD_SET( ), FD_CLR( ), FD_ISSET( ), and<br />

FD_ZERO( ), which are normally implemented as preprocessor macros. Instead, we<br />

will implement them as functions because we need to do a little extra work, and it<br />

also helps ensure type safety:<br />

void spc_fd_zero(SPC_FD_SET *fdset) {<br />

fdset->fds_bits = 0;<br />

fdset->fds_size = 0;<br />

}<br />

void spc_fd_set(int fd, SPC_FD_SET *fdset) {<br />

long *tmp_bits;<br />

size_t new_size;<br />

if (fd < 0) return;<br />

if (fd > fdset->fds_size) {<br />

new_size = sizeof(long) * ((fd + sizeof(long) - 1) / sizeof(long));<br />

if (!(tmp_bits = (long *)realloc(fdset->fds_bits, new_size))) return;<br />

fdset->fds_bits = tmp_bits;<br />

fdset->fds_size = new_size;<br />

}<br />

fdset->fds_bits[fd / sizeof(long)] |= (1 fdset->fds_size) {<br />

new_size = sizeof(long) * ((fd + sizeof(long) - 1) / sizeof(long));<br />

if (!(tmp_bits = (long *)realloc(fdset->fds_bits, new_size))) return;<br />

fdset->fds_bits = tmp_bits;<br />

fdset->fds_size = new_size;<br />

}<br />

fdset->fds_bits[fd / sizeof(long)] |= (1

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

Saved successfully!

Ooh no, something went wrong!