|
Manipulating (set/reset) the bits in such a large bit array requires the use of macros
|
Example:
|
I will first show you how to use select( ) with an int (32 bit) bit array.
|
int s = 0; // Clear all bits
|
s = s | (1 << i);
|
int fdset; // bit array of 32 bits
int s; // socket
// Assume s is initialized and bound to some port...
/* ===========================================
Set up timeout value
=========================================== */
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50; // 50 micro sec time out
/* =============================================
Prepare file descriptors for select( )
============================================= */
fdset = 0; // Clear bit array
fdset = fdset | (1 << s); // s = an initialized socket variable
/* ===================================================
Check for message arrival with in timeout
=================================================== */
if ( select( 32, &fdset, NULL, NULL, &timeout) != 0 )
{
// s is read for reading
}
else
{
// timeout occured
}
|
// 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
================================== */
int recv_fds; /* I can use a simple int */
struct timeval timeout; /* Time value for time out */
/* ===============================
Select the bit for socket s
=============================== */
recv_fds = 0; // Clear all bits in recv_fds
recv_fds = recv_fds | ( 1 << s ); // 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(32, (fd_set *)&recv_fds, NULL, NULL, &timeout);
printf("select( ) returns: %d\n", result);
|
How to run the program:
|