Is there a way to associate a file descriptor with user data?

I am writing a client-server application and use the POSIX function pollto provide a form of simultaneous client processing. Customers also have status data and other related data that are stored in the client structure.

My immediate problem is that when I get a hint from pollI / O in the socket file descriptor that is associated with the client (conceptually), I have to actually match the file descriptor with its associated composition client data. I'm currently doing a search O(n_clients)(my client data structure stores a handle), but I was wondering if there is a better alternative?

+5
source share
4 answers

No. If this were possible, it would have to be tracked by the kernel, and therefore the search for this data would require a system call. The cost of a system call is an order of magnitude more expensive than finding O (n) in user space.

How many clients do you deal at once? If it does not cost hundreds or more, the cost of the search will be minimal compared to the cost of any I / O.

Instead of using O (n) search, you can also just use an array indexed by a file descriptor, provided that you cannot open several specific descriptors at once. For instance:

#define MY_MAX_FD 1024  // Tune this to your needs
void *per_fd_data[MY_MAX_FD];

void *get_per_fd_data(int fd)
{
    assert(fd >= 0);
    if(fd < MY_MAX_FD)
        return per_fd_data[fd];
    else
    {
        // Look up fd in a dynamic associative array (left as an exercise to the
        // reader)
    }
}
+4
source

- {state, * context,..., , } , fd (= O (1 )). , .

EDIT: . fdset : ; getdtablesize() getrlimit(), .

+2

poll() select()/pselect(), , - , . . . , - (, aio_read()), sigev_value, . Linux epoll .

+1

, , , , , .

, , POSIX, http://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_14, ( ):

, , , , ( ) . (, pipe() socketpair()), , , , .

, , , - , . , , . , , , , - 10, 11 , , , POSIX- 10. fd.

+1
source

All Articles