Chethan Prakash
Chethan Prakash

Reputation: 21

c-select() identify first fd that unblocked select for read/recv operation

Given list of Client FDs (eg: 98,99,100) and data is received on FD 99, 100 at the same time Select unblocks and read FDs contains FD:99 and FD: 100

How to determine, which is the first FD on which data has come first??

If I check serially through the list of client FD's that I have in my array it will always try to do socket read on FD: 99. But my application must read the data from FD : 100 as data is received on that FD first.

FD_ZERO(&readfds);
FD_SET(98, &readfds);
FD_SET(99, &readfds);
FD_SET(100, &readfds);
gMaxfd=100;
rc = select(gMaxfd+1, &readfds, NULL, NULL, NULL);
if(rc>0){
    /* Handle the fds for read operation */
    /* Here how to identify which is the first FD on which recv has to be called first ???*/
}

Upvotes: 2

Views: 163

Answers (2)

You want to implement some round-robin scheduling. So use poll(2) and remember the previously processed file descriptor. BTW, as answered by Wumpus your multiplexing syscall (poll or select ...) will usually give one (or a few) readable file descriptors.

Alternatively, read from all the readable file descriptors before restarting your event loop

Notice that both UDP and TCP are byte oriented, without any notion of message packet (at application level). See ip(7), udp(7), tcp(7), Internet Protocol Suite, and remember that TCP is only a byte stream without any packet or message boundaries at application level: a given single send(2) on one end can be on the other side gotten thru several recv(2) (or vice versa several send can be coalesced into one recv etc...). Your application has to buffer and your protocol has to define the message boundaries. Routers between emitter and receiver are allowed to -and do- chunk and join data "packets" at will and at random!

Upvotes: 0

user2404501
user2404501

Reputation:

If there was any significant delay between the events that made those file descriptors readable, select would have returned with the first one without waiting for the second one. So if you get multiple fds, you should treat the events as happening simultaneously.

If simultaneous messages from different sources break your higher-level protocol, you need to redesign it.

Upvotes: 1

Related Questions