Graeme
Graeme

Reputation: 4592

Spoofing file descriptor in C++

I'm writing an library which will transmit data via multiple routes; TCP, UDP, RDMA (Remote Direct Memory Access) and occasionally via a straight function call where client/server are rolled into a single binary.

I'll be handling TCP, UDP, RDMA with file descriptors and have been looking at how I could achieve somethign similar with a FunctionCallSocket class which would take the rough form:

class FunctionCallSocket
{
    public:
        FunctionCallSocket();
        ~FunctionCallSocket();

        void send(char* buf, std::size_t len);
        void recv(char* dest, std::size_t len);

    private:
        char*  m_outboundBuffer;
        char*  m_inboundBuffer;
};

I'd like to do is be able to treat the class like a file descriptor whereby I could pass it along with TCP, UDP, etc. file handles to a select/epoll.

From what I understand the file descriptor integer value is generated by the OS from a privately held table which maps files to id's so I'd somehow need to spoof this.

Any thoughts on how I could achieve this?

Upvotes: 1

Views: 1109

Answers (3)

Steve Lorimer
Steve Lorimer

Reputation: 28659

If you're running on Linux, I suggest looking into eventfd - this does exactly what you're looking for.

http://www.kernel.org/doc/man-pages/online/pages/man2/eventfd.2.html

Open the fd in EFD_SEMAPHORE mode and you can use it to keep track of how many queued events you have

(each write() call will increment the counter stored by the kernel with the eventfd, and each read() will decrement the counter)

Upvotes: 2

Simon Richter
Simon Richter

Reputation: 29598

If it isn't a file descriptor, then there is no point in passing it to select(). If there is a file descriptor somewhere underneath, then you either need an API to expose it, or you have a low-level API to add file descriptors to the select set and make the class responsible for registering any file descriptors it uses. Note that you are well into asynchronous event handling and callback territory then.

Upvotes: 0

templatetypedef
templatetypedef

Reputation: 372814

You could use OS-specific calls to get file descriptors, if you want to. For example, the Unix open function would do just what you want.

Alternatively, you could make your code to read and write data part of a polymorphic class hierarchy, which would let you use file descriptors where appropriate and the streams library (for example) for file I/O. In fact, one idea might be to writw custom stream classes to wrap up the TCP connections, then use ostream and istream as wrappers around the specifics of the connection.

Upvotes: 1

Related Questions