简体   繁体   中英

Non-OS Specific FD(File Descriptor) for C/C++

Linux is also treated as a file, a network socket. but, Windows is not. and common files and network sockets treated as "FD". if the code should not rely on the operating system, how should write?

i think it like below..

#ifndef INVALID_SOCKET
#define INVALID_SOCKET (-1)
#endif

class Descriptor {
private:
   int m_fd;

public:
   Descriptor() : m_fd(INVALID_SOCKET) { }
   virtual ~Descriptor() { this->close(); }
   virtual bool isValid();
   virtual bool close() = 0;
   virtual int getNo() { return m_fd; }
};

enum EListenFlags {
   E_LISTEN_READ = 1,
   E_LISTEN_WRITE = 2,
   E_LISTEN_ERROR = 4,
   E_LISTEN_NONBLOCK = 8
};

class AsyncDescriptor : public Descriptor {
// like EPoll (for linux) or IOCP (for Windows) or SELECT, POLL...
public:
   virtual bool listen(Descriptor* pDesc, int listenFlags) = 0;
   virtual bool dizzy(Descriptor* pDesc, int dizzyFlags) = 0;
   virtual bool wait(std::list<Descriptor*>& listOut) = 0;
   virtual bool list(std::list<Descriptor*>& listOut) = 0;
   virtual bool getFlags(Descriptor* pDesc, int* flagOutput) = 0;
};

class SocketDescriptor : public Descriptor {
     // Omitted.......
};

// Details are omitted below ...

How can i implement it???! :(

Why not use Asio? Does it not do what you want to do?

https://think-async.com/

You cannot do that (getting a non-OS specific file descriptor, or portably dealing with network sockets without any OS support). File descriptors & network sockets are an Operating System specific thing (or in the POSIX standard). The C standard library (from C99 or C11 standards) does not know them. fileno(3) is POSIX 2001 (and also in POSIX 2008).

If coding in C++, you might use framework libraries like POCO or Qt (or perhaps Boost ) wrapping some OS services (eg for Linux, MacOSX, Windows, Android) and providing you with some unified abstractions. If coding in C, you could consider Glib and/or Gio (from GNOME/GTK).

BTW, you want some multiplexing ability (like the poll(2) syscall provides on Linux & POSIX), and it is operating system specific. You could also consider using some event loop library, like eg libev or libevent (or use the event loop facilities from Qt, from POCO, from GTK or Glib)

Notice that C & C++ are different languages, and both can exist on implementations without any networking facilities (eg computers without network abilities, embedded systems, etc...).

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