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> 59Return ValueReturns the number of elements in the ufds array that have had event occur on them; this canbe zero if the timeout occurred. Also returns -1 on error (and errno will be set accordingly.)Exampleint s1, s2;int rv;char buf1[256], buf2[256];struct pollfd ufds[2];s1 = socket(PF_INET, SOCK_STREAM, 0);s2 = socket(PF_INET, SOCK_STREAM, 0);// pretend we’ve connected both <strong>to</strong> a server at this point//connect(s1, ...)...//connect(s2, ...)...// set up the array of file descrip<strong>to</strong>rs.//// in this example, we want <strong>to</strong> know when there’s normal or out-of-band// data ready <strong>to</strong> be recv()’d...ufds[0].fd = s1;ufds[0].events = POLLIN | POLLPRI; // check for normal or out-of-bandufds[1] = s2;ufds[1].events = POLLIN; // check for just normal data// wait for events on the sockets, 3.5 second timeoutrv = poll(ufds, 2, 3500);if (rv == -1) {perror("poll"); // error occurred in poll()} else if (rv == 0) {printf("Timeout occurred! No data after 3.5 seconds.\n");} else {// check for events on s1:if (ufds[0].revents & POLLIN) {recv(s1, buf1, sizeof(buf1), 0); // receive normal data}if (ufds[0].revents & POLLPRI) {recv(s1, buf1, sizeof(buf1), MSG_OOB); // out-of-band data}}// check for events on s2:if (ufds[1].revents & POLLIN) {recv(s1, buf2, sizeof(buf2), 0);}See Alsoselect()

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

Saved successfully!

Ooh no, something went wrong!