c++ - 如何在 C++ 中读取最多 X 秒?

标签 c++ timeout file-descriptor

我希望我的程序等待读取 FIFO 中的内容,但是如果 read(我使用 std::fstream)持续超过 5 秒,我想要它退出。

有可能还是我必须绝对使用alarm

谢谢。

最佳答案

我不相信有一个干净的方法来完成这个,即仅可移植的 C++ 解决方案。您最好的选择是在基于 *nix 的系统上使用 pollselect,在 Windows 上使用 WaitForSingleObjectWaitForMultipleObjects

您可以通过创建一个代理 streambuffer 类来透明地完成此操作,该类将调用转发给真正的 streambuffer 对象。这将允许您在进行实际读取之前调用适当的 wait 函数。它可能看起来像这样......

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_;
};

您需要在每次通话时都这样做。它可能会有点乏味,但会提供一个透明的解决方案来提供超时,即使在客户端代码中可能未明确支持超时也是如此。

关于c++ - 如何在 C++ 中读取最多 X 秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16113989/

相关文章:

c++ - Boost::Signals 的意义何在?

c++ - C++ 标准库在任何时候都包含每个平台的 native 头文件吗?

c++ - 当他们互相调用时如何在同一个类中模拟函数

c++ - 测量耗时,将开始时间存储为原始类型

tcp - set_timeout() 在 TcpStream 上究竟是如何工作的?

c# - SQL Server 长时间运行的查询通过 .Net 随机超时

cuda - 启动 CUDA-Kernel 并设置超时

c - 桥接两个文件描述符

c - 在一个进程 fork 并且我们有一个新的克隆进程之后,关闭子表中的文件会影响父表中的表吗?

python - 如果 fd 超出本地范围,Python 会关闭它吗?