我希望我的程序等待在先进先出中读取一些东西,但是如果read (我使用std::fstream)持续超过5秒,我希望它退出。
有没有可能,或者我一定要使用alarm?
谢谢。
发布于 2013-04-20 06:35:41
我不相信有一个干净的方式来完成这一点,那就是可移植的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_;
};您需要在每次调用时执行此操作。它可能有点单调乏味,但将为提供超时提供一个透明的解决方案,即使在客户端代码中可能没有显式支持超时。
发布于 2013-04-20 07:02:21
对于我解决问题的方式,下面是我从我的流中读取的函数。
std::string
NamedPipe::readForSeconds(int seconds)
{
fd_set readfs;
struct timeval t = { seconds, 0 };
FD_ZERO(&readfs);
FD_SET(this->_stream, &readfs);
if (select(this->_stream + 1, &readfs, NULL, NULL, &t) < 0)
throw std::runtime_error("Invalid select");
if (FD_ISSET(this->_stream, &readfs))
return this->read();
throw NamedPipe::timeoutException();
}https://stackoverflow.com/questions/16113989
复制相似问题