简体   繁体   中英

Is it guaranteed that socket descriptors in linux/freebsd will have almost sequential or comparable numbers?

I understand that there is nothing preventing linux to assign descriptors any random numbers in range 0...2^32 when I create new socket. But what reality is? In my application (web server) I need a mapping structure that maps descriptor into a "connection structure". I understand that some kind of RB-Tree (int -> connection_ptr*) will work, but linear array of connection_ptr pointers (where each pointer placed at offset (index) = descriptor value) would be a little faster.

File descriptors are always assigned from the lowest available number. This is guaranteed by POSIX.

Even if it were implemented that way, if you care for portability and reliability, you cannot rely on that.

To get almost constant access complexity, you can use a hashed container, like std:unordered_map . You can even write a custom hasher, so the storage will be optimized for the file descriptor number distribution.

struct SocketHasher {
    size_t operator()(uint32_t key) {
        return key & 0xFFFF;
    }
}
std::unordered_map<uint32_t, connection_ptr, SocketHasher> connectionPool;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM