Search code examples
c++timeoutfile-descriptor

How to read for X seconds maximum in C++?


I want my program to wait for something to read in a FIFO, but if the read (I use std::fstream) lasts more than 5 seconds, I want it to exit.

Is it possible or do I have to use alarm absolutely?

Thank you.


Solution

  • I do not believe there is a clean way to accomplish this that is portable C++ only solution. Your best option is to use poll or select on *nix based systems and WaitForSingleObject or WaitForMultipleObjects on Windows.

    You can do this transparently by creating a proxy streambuffer class that forwards calls to a real streambuffer object. This will allow you to call the appropriate wait function before doing the actual read. It might look something like this...

    class MyStreamBuffer : public std::basic_streambuf<char>
    {
    public:
        MyStreamBuffer(std::fstream& streamBuffer, int timeoutValue)
            : timeoutValue_(timeoutvalue),
              streamBuffer_(streamBuffer)
        {
        }
    
    protected:
        virtual std::streamsize xsgetn( char_type* s, std::streamsize count )
        {
            if(!wait(timeoutValue_))
            {
                return 0;
            }
    
            return streamBuffer_.xsgetn(s, count);
         }
    
    private:
         bool wait() const
         {
             // Not entirely complete but you get the idea
             return (WAIT_OBJECT_0 == WaitForSingleObject(...));
         }
    
        const int       timeoutValue_;
        std::fstream&   streamBuffer_;
    };
    

    You would need to do this on every call through. It might get a little tedious but would provide a transparent solution for providing timeouts even where they might not be explicitly supported in client code.