|
|
#include <poll.h> |
|
|
struct pollfd { int fd; // A descriptor (e.g., socket) short events; // This is a bit array // Each bit represents a certain operation // Set that bit to check for readiness // E.g, one or the bit represent receive short revents; // ready events // This is also a bit array // Each bit represents whether some operation is ready } |
Meaning of the parameters:
fd = the (one) file descriptor/socket to be checked events = input bit array of events that will be checked revents = output bit array of events that are ready |
The types of events are defined by the following bit masks:
POLLIN (= 00001) = ready for input (receive) POLLOUT (= 00010) = ready for output (send) |
|
|
|
|
Solution:
Define an pollfd arary of 1 element:
Initialize the poll structure fd[0] to test s for read readiness:
Call poll( ) with timeout:
|
|
Solution:
Define a pollfd arary of 2 elements (because we have 2 sockets):
Initialize the poll structure fd[0] to test s1 for read readiness:
Call poll( ):
|
// I need to create a scoket and bind it first.... /* --- Create a socket --- */ s = socket(PF_INET, SOCK_DGRAM, 0); /* --- Set up socket end-point info for binding --- */ in_addr.sin_family = AF_INET; /* Protocol family */ in_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Wildcard IP address */ in_addr.sin_port = htons(atoi(argv[1])); /* Use any UDP port */ /* --- Bind socket s --- */ bind(s, (struct sockaddr *)&in_addr, sizeof(in_addr)) /* ============================================== How to use poll( ) ============================================== */ struct pollfd fds[1]; // 1 socket int timeout = 5000; // 5000 msec = 5 sec /* ====================================== Set up fds[0] to monitor socket s ====================================== */ fds[0].fd = s; // Test socket s fds[0].events = 0; // Clear events fds[0].events = fds[0].events | POLLIN; ; // Set INPUT bit int result ; printf("Now use udp4-s3 and send a UDP message to port %s before %d sec\n", argv[1], timeout/1000 ); /* ================================ Here we go.... ================================ */ result = poll( fds, 1, timeout ); printf("poll( ) returns: %d\n", result); |
How to run the program:
|