13.07.2015 Views

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

Beej’s <strong>Guide</strong> <strong>to</strong> <strong>Network</strong> <strong>Programming</strong> <strong>Using</strong> <strong>Internet</strong> <strong>Sockets</strong> 588.14. poll()Test for events on multiple sockets simultaneouslyPro<strong>to</strong>types#include int poll(struct pollfd *ufds, unsigned int nfds, int timeout);DescriptionThis function is very similar <strong>to</strong> select() in that they both watch sets of file descrip<strong>to</strong>rs forevents, such as incoming data ready <strong>to</strong> recv(), socket ready <strong>to</strong> send() data <strong>to</strong>, out-of-band dataready <strong>to</strong> recv(), errors, etc.The basic idea is that you pass an array of nfds struct pollfds in ufds, along with atimeout in milliseconds (1000 milliseconds in a second.) The timeout can be negative if you want<strong>to</strong> wait forever. If no event happen on any of the socket descrip<strong>to</strong>rs by the timeout, poll() willreturn.Each element in the array of struct pollfds represents one socket descrip<strong>to</strong>r, and containsthe following fields:struct pollfd {int fd;short events;short revents;};// the socket descrip<strong>to</strong>r// bitmap of events we’re interested in// when poll() returns, bitmap of events that occurredBefore calling poll(), load fd with the socket descrip<strong>to</strong>r (if you set fd <strong>to</strong> a negative number,this struct pollfd is ignored and its revents field is set <strong>to</strong> zero) and then construct the eventsfield by bitwise-ORing the following macros:POLLINPOLLOUTAlert me when data is ready <strong>to</strong> recv() on this socket.Alert me when I can send() data <strong>to</strong> this socket without blocking.POLLPRIAlert me when out-of-band data is ready <strong>to</strong> recv() on this socket.Once the poll() call returns, the revents field will be constructed as a bitwise-OR of theabove fields, telling you which descrip<strong>to</strong>rs actually have had that event occur. Additionally, theseother fields might be present:POLLERRAn error has occurred on this socket.POLLHUPPOLLNVALThe remote side of the connection hung up.Something was wrong with the socket descrip<strong>to</strong>r fd–maybe it’suninitialized?

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

Saved successfully!

Ooh no, something went wrong!