Main Page   Namespace List   Class Hierarchy   Alphabetical List   Compound List   File List   Namespace Members   Compound Members   File Members  

FileDescriptor.h

Go to the documentation of this file.
00001 /* -*- c++ -*- */
00002 #ifndef MPS_FileDescriptor_H
00003 #define MPS_FileDescriptor_H
00004 
00005 #include <sys/time.h>
00006 #include <sys/types.h>
00007 #include <unistd.h>
00008 
00009 #ifdef __WIN32__
00010 #include <winsock.h>
00011 #endif
00012 
00013 #include <ref.h>
00014 #include <exception>
00015 #include <string>
00016 #include <vector>
00017 #include <map>
00018 #include <algorithm>
00019 
00020 class FileDescriptor;
00021 class FileDescriptorManager;
00022 
00023 /**
00024  * Associates callbacks with events on a given Unix File Descriptor,
00025  * and provides an interface to Unix system calls dealing with file
00026  * descriptors. Works in association with a FileDescriptorManager. */
00027 class FileDescriptor: public Referenceable {
00028 public:
00029   //---------------------------------------------------------------------------
00030   /**
00031    * Thrown by methods on FileDescriptor and subclasses. Compatible
00032    * with std::exception. */
00033   class Exception: public std::exception {
00034   private:
00035     string message;     ///< Description of the error condition
00036     int savedErrno;     ///< Errno at the time of the error; zero if none available
00037 
00038   public:
00039     Exception(string const &msg, int _savedErrno = 0)
00040       : message(msg),
00041         savedErrno(_savedErrno)
00042     {}
00043 
00044     virtual char const *what() const { return message.c_str(); }        ///< Extract error msg
00045     int getErrno() const { return savedErrno; }                         ///< Extract saved errno
00046   };
00047 
00048   /**
00049    * Subclass of FileDescriptor::Exception for indicating end-of-file
00050    * conditions to callers. */
00051   class EndOfFile: public Exception {
00052   public:
00053     EndOfFile(string const &msg)
00054       : Exception(msg)
00055     {}
00056   };
00057   //---------------------------------------------------------------------------
00058 
00059   /**
00060    * Subclass this to provide callback-methods to be called by methods
00061    * on FileDescriptor and subclasses. */
00062   class Callback: public Referenceable {
00063   public:
00064     /**
00065      * All callbacks called by FileDescriptor methods must be of this
00066      * type. The single argument, desc, is the FileDescriptor that the
00067      * event occurred on. */
00068     typedef void (Callback::*Method)(ref<FileDescriptor> const &desc);
00069   };
00070 
00071 private:
00072   ref<FileDescriptorManager> fdMgr;             ///< The FileDescriptorManager that manages this
00073   int fd;                                       ///< Unix fd we are wrapping
00074   char buf[1024];                               ///< Input buffer (output is unbuffered)
00075   int buflen;                                   ///< Number of bytes in the buffer
00076   int pos;                                      ///< Index of next byte to return
00077 
00078   /// Describes a particular bound callback
00079   struct callback_entry_t {
00080     ref<Callback> callback;                     ///< The callback itself
00081     Callback::Method callbackMethod;            ///< The method to invoke on the callback
00082 
00083     callback_entry_t()
00084       : callback(0),
00085         callbackMethod(0)
00086     {}
00087   };
00088 
00089   callback_entry_t readCallback;                ///< Callback for read-available
00090   callback_entry_t writeCallback;               ///< Callback for write-available
00091 
00092   /// Fill buffer with at least one byte. Returns true if okay, false if would block.
00093   bool fillBuffer();
00094 
00095   // Disallow copy ctor etc.
00096   FileDescriptor(FileDescriptor const &other);
00097   FileDescriptor const &operator=(FileDescriptor const &other);
00098 
00099   /**
00100    * Updates the fd_set objects in our FileDescriptorManager depending
00101    * on whether we are interested in read-available, write-available,
00102    * or both conditions. */
00103   void updateCallbacks();
00104 
00105 protected:
00106   /**
00107    * Override, eg. for sockets on Linux, where you can use
00108    * ::send(... MSG_NOSIGNAL) etc., and for sockets on Win32 where you
00109    * have to use recv and send instead of read and write. Default
00110    * (superclass) behaviour is to use ::write and ::read. */
00111   //@{
00112   virtual int lowlevel_read(int handle, char *buf, int len);
00113   virtual int lowlevel_write(int handle, char const *buf, int len);
00114   virtual int lowlevel_close(int handle);
00115   //@}
00116 
00117 public:
00118   /// This constructor wraps the passed in _fd in association with the passed in _fdMgr.
00119   FileDescriptor(ref<FileDescriptorManager> const &_fdMgr, int _fd);
00120 
00121   /// The file-descriptor is close()d on destruction.
00122   virtual ~FileDescriptor();
00123 
00124   bool isOpen() const { return (fd != -1); }    ///< true -> this fd is open.
00125 
00126   /// true -> some bytes are available for read *now*.
00127   bool inputReady() {
00128     fillBuffer();
00129     return isOpen() && (pos < buflen);
00130   }
00131 
00132   int getFd() const { return fd; }              ///< Access the file descriptor wrapped by this.
00133   ref<FileDescriptorManager> const &getFdMgr() const;   ///< Access our controlling fdMgr
00134 
00135   virtual void close();                         ///< Closes this fd.
00136 
00137   bool setNonBlocking(bool on);                 ///< true -> success
00138 
00139   //@{
00140   /// Installs a callback for read-available events.
00141   void setReadCallback(ref<Callback> const &cb, Callback::Method cbm);
00142   /// Installs a callback for write-available events.
00143   void setWriteCallback(ref<Callback> const &cb, Callback::Method cbm);
00144 
00145   /// Clear our read-available callback - we are no longer interested in those events
00146   void clearReadCallback();
00147   /// Clear our write-available callback - we are no longer interested in those events
00148   void clearWriteCallback();
00149 
00150   void fireReadCallback();      ///< Calls the read-callback; does not clear the callback
00151   void fireWriteCallback();     ///< Calls the write-callback; does not clear the callback
00152   //@}
00153 
00154   /**
00155    * Calls select() to wait for some event on this fd only; all others
00156    * are ignored.
00157    *
00158    * %%% (NOTE: should probably be protected rather than public; don't
00159    * %%% call it unless you're sure you know what you're doing - and
00160    * %%% let tonyg@kcbbs.gen.nz know if you *do* find a legitimate use
00161    * %%% for it!) */
00162   void block(bool forRead, bool forWrite);
00163 
00164   //@{
00165   /**
00166    * These process as many bytes as possible without blocking, and
00167    * return the number of bytes processed, unless 'complete' is set,
00168    * in which case they keep working until exactly len bytes have been
00169    * processed or an exception is met. */
00170   int read(char *inbuf, int len, bool complete = false);
00171   int write(char const *outbuf, int len, bool complete = false);
00172   //@}
00173 
00174   /// Read a single byte.
00175   bool read(int &ch) {
00176     if (!fillBuffer())
00177       return false;
00178     ch = buf[pos++];
00179     return true;
00180   }
00181 };
00182 
00183 /**
00184  * Manages a collection of FileDescriptors, using fd_sets and
00185  * select(). */
00186 class FileDescriptorManager: public Referenceable {
00187 private:
00188   typedef vector< ref<FileDescriptor> > descVec_t;      ///< Allow lookup of object from fd number
00189 
00190   descVec_t allFds;     ///< All FileDescriptor objects registered with this fdMgr
00191   int countRegistered;  ///< Count of registered FileDescriptor objects
00192   int maxFd;            ///< Maximum fd number of all registered FileDescriptors
00193   fd_set readFds;       ///< Set of fds interested in read-available events
00194   fd_set writeFds;      ///< Set of fds interested in write-available events
00195 
00196   //@{
00197   friend class FileDescriptor;
00198   /// Adds, updates or disables the entry for a given FileDescriptor.
00199   void update(ref<FileDescriptor> const &fd, bool forRead, bool forWrite);
00200   /// Removes the entry for a given FileDescriptor completely.
00201   void remove(int fdnum);
00202   //@}
00203 
00204 public:
00205   FileDescriptorManager();
00206 
00207   void closeAll();              ///< Force close all FileDescriptors managed by this
00208 
00209   //@{
00210   int getMaxFd() const { return maxFd; }                ///< Returns the maximum FD managed
00211   void fillFdSet(fd_set *rfds, fd_set *wfds) const;     ///< Fills in all entries for managed fds
00212   void processFdSet(fd_set *rfds, fd_set *wfds);        ///< Runs work from a post-select() fdset
00213   //@}
00214 
00215   //@{
00216   /**
00217    * Wait for incoming work for up to the given timeout, or forever if
00218    * timeout is NULL.
00219    *
00220    * @return true for "work processed"; false for "timed out" */
00221   bool poll(struct timeval const *timeout);
00222 
00223   /// Repeatedly calls poll(NULL).
00224   void mainloop();
00225   //@}
00226 
00227   //@{
00228   /// Statistics.
00229   int getCountRegistered() const { return countRegistered; }
00230   //@}
00231 };
00232 
00233 #endif

Generated at Wed Aug 15 01:05:15 2001 for mps-cpp by doxygen1.2.6 written by Dimitri van Heesch, © 1997-2001