David Rysdam wrote:
> Moisés Navarro Marín wrote:
> >
> > Hi.
> >
> > I'm using 'select' to detect which client is sending information to
> > the server. So I got the following code:
> >
> > ==============================
> >
> > while (TRUE)
> > {
> > FD_ZERO (&clients_fds); /* This call to FD_ZERO is here to update
> > the info about active clients in every loop*/
> > for (i=0; i < MAX_CONNECTIONS; i++)
> > if (client_sockets[i].socket > 0)
> > FD_SET (client_sockets[i].socket, &clients_fds);
> >
> > numSelected = select (max_fd (client_sockets)+1, &clients_fds,
> > (fd_set *) 0, (fd_set *) 0, (struct timeval *) 0);
> >
> > ...
> > }
> >
> > ===============================
> >
> > Well, the question is what am I doing wrong because 'select' never
> > returns even though client is calling 'sock_write' in an infinite loop
> > without errors!!! :?
>
I have to apologize because I sent my mail too soon and I forgot to explain some
questions before...
> First, I think you want to start your select with:
>
> select(max_fd (i), ...)
No. In this case 'max_fd' is a function which returns the biggest file descriptor
contained in a vector of fd's...
So taking:
client_sockets[0]=3
client_sockets[1]=6
max_fd (client_sockets) returns 6.
The real call to max_fd would be 'max_fd (client_sockets, 2 /* lenght */)'.
> Secondly, I don't understand the first part. Why zero out the clients
> and then re-set them? A better idea is to create a "pristine" fd struct
> that you can just copy over the returned one every time. Your loop
> apparently figures out which sockets are still active, but select can do
> that for you because a file descripter will come back as readable with 0
> bytes and you can close it (marking your "pristine" structure at the
> same time). This will cut out a loop from your server.
The code above is part of a multithreaded server. Some threads are waiting for
clients for starting or for ending a session and other threads are about relaying
information.
So the first kind of threads add or delete entries in 'client_sockets' and the
second kind of threads just wait for activity on any of the active sockets present
in 'client_sockets'.
As some of these sockets may be closed or new sockets may have been started during
the infinite loop I used FD_ZERO and FD_SET to keep the list of active sockets
updated.
> I have a very short (200 lines) IRC-like server/client written to teach
> myself about select (and sockets) that illustrates this that I'd be
> happy to share with you.
Sure it will help me on this mess. Please, send it to me. Thanks a lot!!! :)
Moises Navarro.