I used select for synchronous I/O multiplexing.It will check for any data for 1 second.After 1 second if no data it will display a output (puts("Waited for 1 sec no data");) then it will check again for data.But this is working only at first time then it enters endless loops.
Is there any alternative solution for this.
//..............................
//.............................
//Creating listener socket and other sort of things
struct timeval tv;
tv.tv_sec=1;
tv.tv_usec=0;
while(1)
{
FD_ZERO(master);
FD_SET(listener,master);
fdmax = listener;
int retval=select(fdmax+1,master, NULL, NULL,&tv);
printf("retval is %d\n",retval);
if(retval == -1)
{
perror("Server-select() error");
}else if(retval)
{
puts("Data available");
//If there is no data do some work and checkagain.
}else
{
puts("Waited for 1 sec no data");
//If there is no data do some work and checkagain.
}
}
From man select:
On Linux, select() modifies timeout to reflect the amount of time not slept; most other implementations do not do this. (POSIX.1-2001 permits either behavior.) This causes problems both when Linux code which reads timeout is ported to other operating systems, and when code is ported to Linux that reuses a struct timeval for multiple select()s in a loop without reinitializing it. Consider timeout to be undefined after select() returns.
So like master, you will have to set tv before each select call.
In my codes, I often have something like:
FD_ZERO(master);
FD_SET(listener,master);
fdmax = listener;
while (1)
{
struct timeval tv = {1, 0};
int retval=select(fdmax+1,master, NULL, NULL,&tv);
printf("retval is %d\n",retval);
if(retval == -1) {
perror("Server-select() error");
break; // <-- notice the break here
} else if(retval) {
puts("Data available");
} else {
puts("Waited for 1 sec no data");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With