|
fd_set recv_fds ; |
The fd_set variable is:
|
int recv_fds ; // int is a bit array of 32 bits |
This will work as long as you use ≤ 32 descriptors (i.e., use less than around 30 sockets !!!)
fd_set recv_fds; // bit array variable int s = socket(PF_INET, SOCK_DGRAM, 0); // Socket that we want to // test for receive readiness (1) clear all bits in the bit array variable recv_fds (2) set the bit position s in the bit array variable recv_fds (3) call: select ( FD_SETSIZE, &recv_fds, NULL, NULL, timeout ) |
int recv_fds; // Shorter bit array variable int s = socket(PF_INET, SOCK_DGRAM, 0); // Socket that we want to // test for receive readiness (1) clear all bits in recv_fds recv_fds = 0 (2) set the bit position s in recv_fds recv_fds = recv_fds | ( 1 << s ) (3) Call: select ( 32, &recv_fds, NULL, NULL, timeout ); (I need to use 32 to tell select( ) that it only need to scan the first 32 entries in the descriptor table) |
|
I have highlighted the changes
// 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 select ================================== */ fd_set recv_fds; /* I'm using a fd_set var now */ struct timeval timeout; /* Time value for time out */ /* =============================== Select the bit for socket s =============================== */ FD_ZERO( &recv_fds ); // Clear all bits in recv_fds FD_SET( s, &recv_fds); // Set bit for socket s /* =================================== Set timeout value to 5 sec =================================== */ timeout.tv_sec = 5; // Timeout = 5 sec + 0 micro sec timeout.tv_usec = 0; // number of micro seconds int result ; printf("Now send a UDP message to port %s before %d sec !!!....\n", argv[1], timeout.tv_sec ); result = select(FD_SETSIZE, &recv_fds, NULL, NULL, &timeout); printf("select( ) returns: %d\n", result); |
How to run the program:
|