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.

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

if (fd < 0 || fd >= fdset->fds_size) return 0;<br />

return (fdset->fds_bits[fd / sizeof(long)] & (1 fds_bits) free(fdset->fds_bits);<br />

}<br />

int spc_fd_setsize(SPC_FD_SET *fdset) {<br />

return fdset->fds_size;<br />

}<br />

Notice that we’ve added two additional functions, spc_fd_free( ) and spc_fd_<br />

setsize( ). Because we are now dynamically allocating the array, there must be some<br />

way to free it. The function spc_fd_free( ) will only free the inner contents of the<br />

SPC_FD_SET object passed to it, leaving management of the SPC_FD_SET object up to<br />

you—you may allocate these objects either statically or dynamically. The other function,<br />

spc_fd_setsize( ), is a replacement for the FD_SETSIZE macro that is normally<br />

used as the first argument to select( ), indicating the size of the FD_SET objects<br />

passed as the next three arguments.<br />

Finally, using the new code requires some minor changes to existing code that uses<br />

the standard fd_set. Consider the following code example, where the variable<br />

client_count is a global variable that represents the number of connected clients, and<br />

the variable client_fds is a global variable that is an array of socket descriptors for<br />

each connected client:<br />

void main_server_loop(int server_fd) {<br />

int i;<br />

fd_set read_mask;<br />

for (;;) {<br />

FD_ZERO(&read_mask);<br />

FD_SET(server_fd, &read_mask);<br />

for (i = 0; i < client_count; i++) FD_SET(client_fds[i], &read_mask);<br />

select(FD_SETSIZE, &read_mask, 0, 0, 0);<br />

if (FD_ISSET(server_fd, &read_mask)) {<br />

/* Do something with the server_fd such as call accept( ) */<br />

}<br />

for (i = 0; i < client_count; i++)<br />

if (FD_ISSET(client_fds[i], &read_mask)) {<br />

/* Read some data from the client's socket descriptor */<br />

}<br />

}<br />

}<br />

}<br />

The equivalent code using the SPC_FD_SET data type and the functions that operate on<br />

it would be:<br />

void main_server_loop(int server_fd) {<br />

int i;<br />

114 | Chapter 3: Input Validation<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!