我希望我的程序等待读取 FIFO 中的内容,但是如果 read
(我使用 std::fstream
)持续超过 5 秒,我想要它退出。
有可能还是我必须绝对使用alarm
?
谢谢。
最佳答案
我不相信有一个干净的方法来完成这个,即仅可移植的 C++ 解决方案。您最好的选择是在基于 *nix 的系统上使用 poll
或 select
,在 Windows 上使用 WaitForSingleObject
或 WaitForMultipleObjects
。
您可以通过创建一个代理 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/