UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2012-05-23 07:04 PM

Ron Eeeggler
Guest

select()

Hi,

I want to fire a select as soon as there's data in my incoming serial buffer.
My function looks like this and it keeps timing out... :( why is this??? :o

int query_modem(int fd)   // query modem with an AT command
{
int n;
fd_set rdfs;
struct timeval timeout;
ssize_t retval;
char bufptr[100];
char chr;
int cnt = 0;
int i = 0;

// initialise the timeout structure
timeout.tv_sec = 2; // ten second timeout
timeout.tv_usec = 0;

if (FD_ISSET(fd, &rdfs)){
  FD_ZERO(&rdfs);
  FD_CLR(fd,&rdfs);
}

retval = write(fd, "TEST\r", 5);  // send an AT command followed by a CR
/*usleep(50);
while (read(fd, &chr, 1))
 {
 printf("0x%x\n",chr);
 usleep(10);
 }*/

// do the select
n = select(fd + 1, &rdfs, NULL, NULL, &timeout);

// check if an error has occured
if(n < 0)
{
 perror("select failed\n");
}
else if (n == 0)
{
 puts("Timeout!");
}
else
{
 printf("\nBytes detected on the port!\n");
}

}

#2 2012-05-24 12:49 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: select()

timeout.tv_sec = 2; // ten second timeout

Which is the typo: the code or the comment?  Because, they disagree...

if (FD_ISSET(fd, &rdfs)){
  FD_ZERO(&rdfs);
  FD_CLR(fd,&rdfs);
}

Uh, what exactly are you trying to do here?  Because, it seems to make absolutely no sense...  At that point in the function, "rdfs" is completely uninitialized, and contains random junk off the stack...  So, testing it for anything and basing some conditional inialization on it makes no sense...  Plus, what you do in that case doesn't seem to make much sense...  You want an FD_SET() after the FD_ZERO(), not an FD_CLR() (which is just redundant, given the FD_ZERO())...  But, the key thing is you want to do that FD_ZERO() and FD_SET() always!  Otherwise, you leave the fd_set filled with garbage...  Basically, what you're doing right now ensures that "rdfs" will never actually contain "fd", so your later select() will never even be checking for input on "fd"...  You seem to be doing the exact opposite of what you want to do!

Offline

#3 2012-05-24 09:23 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: select()

Another thing to keep in mind is that your character device might
not actually support select(). It probably will, but don't count on it.

I find the poll(2) interface much nicer than the select() one, it
surprises me how many people go straight for select(), especially
for low number of fds.

Offline

#4 2012-05-25 01:09 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,839
Website

Re: select()

Offline

#5 2012-05-26 09:37 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: select()

Offline

Board footer

Powered by FluxBB