为什么我的io_service :: run_one()实现导致无限期阻塞并触发错误#125?

时间:2017-06-08 12:39:28

标签: c++ boost-asio placeholder nonblocking boost-bind

我正在使用BOOST与串行端口进行异步通信。我无法确定我所面临的错误的原因,并希望得到一些指导。

std::string myclass::readStringUntil(const std::string& delim)
{
    setupParameters=ReadSetupParameters(delim);
    performReadSetup(setupParameters);

if(timeout!=posix_time::seconds(0)) timer.expires_from_now(timeout);
else timer.expires_from_now(posix_time::hours(100000));

timer.async_wait(boost::bind(&myclass::timeoutExpired,this,
            asio::placeholders::error));

result=resultInProgress;
bytesTransferred=0;
for(;;)
{
    io.run_one();
    switch(result)
    {
        case resultSuccess:
            {
                timer.cancel();
                bytesTransferred-=delim.size();//Don't count delim
                istream is(&readData);
                string result(bytesTransferred,'\0');//Alloc string
                is.read(&result[0],bytesTransferred);//Fill values
                is.ignore(delim.size());//Remove delimiter from stream
                return result;
            }
        case resultTimeoutExpired:
            port.cancel();
            throw(timeout_exception("Timeout expired"));
            cout<<"timeout on readuntill"<<endl;
        case resultError:
            timer.cancel();
            port.cancel();
            throw(boost::system::system_error(boost::system::error_code(),
                    "Error while reading"));
    }
}

/////////////////////////////////////////////////////////////////////////////

void myclass::performReadSetup(const ReadSetupParameters& param)
{
if(param.fixedSize)
{
    asio::async_read(port,asio::buffer(param.data,param.size),boost::bind(
            &myclass::readCompleted,this,asio::placeholders::error,
            asio::placeholders::bytes_transferred));
} else {
    asio::async_read_until(port,readData,param.delim,boost::bind(
            &myclass::readCompleted,this,asio::placeholders::error,
            asio::placeholders::bytes_transferred));
}
}

/////////////////////////////////////////////////////////////////////////////

void myclass::timeoutExpired(const boost::system::error_code& error)
{
 if(!error && result==resultInProgress) result=resultTimeoutExpired;
}

/////////////////////////////////////////////////////////////////////////////

void myclass::readCompleted(const boost::system::error_code& error,
    const size_t bytesTransferred) 
{
if(!error)
{
    result=resultSuccess;
    this->bytesTransferred=bytesTransferred;
    return;
}

#ifdef _WIN32
if(error.value()==995) return; //Windows spits out error 995
#elif defined(__APPLE__)
if(error.value()==45)
{
    //Bug on OS X, it might be necessary to repeat the setup
    //http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
    performReadSetup(setupParameters);
    return;
}
#else //Linux
if(error.value()==125) return; //Linux outputs error 125
#endif

result=resultError;
}

没有io.run_one(),我进入无限循环而不进入开关案例。

我如何修复我的代码以使其脱离无限期的块?我无法确认,但我认为run_one()导致错误#125

1 个答案:

答案 0 :(得分:0)

首先,错误125是操作中止:这意味着(可能)一个cancel()调用(或导致取消的io对象的析构函数)。

这是正常的。

我已经很难完成你的不完整代码¹并且不容易看到你的问题:

<强> Live On Coliru

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>

struct myclass {
    struct timeout_exception : std::runtime_error {
        timeout_exception(std::string const &msg) : std::runtime_error(msg) {}
    };

    enum {
        resultInProgress,
        resultTimeoutExpired,
        resultSuccess,
        resultError,
    } result = resultInProgress;

    std::string readStringUntil(std::string const &);
    struct ReadSetupParameters {
        ReadSetupParameters(std::string const &d = "") : delim{ d } {}
        std::string delim;
        bool fixedSize = false;
        char mutable data[1024];
        size_t size = sizeof(data);
    };

    void performReadSetup(const ReadSetupParameters &param);

    ReadSetupParameters setupParameters;
    boost::posix_time::time_duration timeout{ boost::posix_time::seconds(3) };
    boost::asio::io_service io;
    boost::asio::deadline_timer timer{ io };

    // more likely a serial port, but I'm not gonna bother mocking that:
    boost::asio::ip::tcp::socket port{ io };
    boost::asio::streambuf readData;
    size_t bytesTransferred;

    myclass() { port.connect({ {}, 6767 }); }

    void timeoutExpired(boost::system::error_code const &ec);
    void readCompleted(boost::system::error_code const &ec, size_t bytesTransferred);
};

std::string myclass::readStringUntil(const std::string &delim) {
    using namespace boost;

    setupParameters = ReadSetupParameters(delim);
    performReadSetup(setupParameters);

    if (timeout != posix_time::seconds(0))
        timer.expires_from_now(timeout);
    else
        timer.expires_from_now(posix_time::hours(100000));

    timer.async_wait(boost::bind(&myclass::timeoutExpired, this, asio::placeholders::error));

    result = resultInProgress;
    for (;;) {
        io.run_one();
        switch (result) {
        case resultSuccess: {
            timer.cancel();
            bytesTransferred -= delim.size(); // Don't count delim
            std::istream is(&readData);
            std::string result(bytesTransferred, '\0'); // Alloc string
            is.read(&result[0], bytesTransferred);      // Fill values
            is.ignore(delim.size());                    // Remove delimiter from stream
            return result;
        } break;
        case resultTimeoutExpired:
            port.cancel();
            std::cout << "timeout on readuntill" << std::endl;
            throw(timeout_exception("Timeout expired"));
            break;
        case resultError:
            timer.cancel();
            port.cancel();
            throw(boost::system::system_error(boost::system::error_code(), "Error while reading"));
        }
    }
}

/////////////////////////////////////////////////////////////////////////////

void myclass::performReadSetup(const ReadSetupParameters &param) {
    using namespace boost;
    if (param.fixedSize) {
        asio::async_read(port, asio::buffer(param.data, param.size),
                         boost::bind(&myclass::readCompleted, this, asio::placeholders::error,
                                     asio::placeholders::bytes_transferred));
    } else {
        asio::async_read_until(port, readData, param.delim,
                               boost::bind(&myclass::readCompleted, this, asio::placeholders::error,
                                           asio::placeholders::bytes_transferred));
    }
}

/////////////////////////////////////////////////////////////////////////////

void myclass::timeoutExpired(const boost::system::error_code &error) {
    if (!error && result == resultInProgress)
        result = resultTimeoutExpired;
}

/////////////////////////////////////////////////////////////////////////////

void myclass::readCompleted(const boost::system::error_code &error, const size_t bytesTransferred) {
    if (!error) {
        result = resultSuccess;
        this->bytesTransferred = bytesTransferred;
        return;
    }

#ifdef _WIN32
    if (error.value() == 995)
        return; // Windows spits out error 995
#elif defined(__APPLE__)
    if (error.value() == 45) {
        // Bug on OS X, it might be necessary to repeat the setup
        // http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
        performReadSetup(setupParameters);
        return;
    }
#else // Linux
    if (error.value() == 125)
        return; // Linux outputs error 125
#endif

    result = resultError;
}

int main() {
    myclass absent;
    std::cout << "Ok: '" << absent.readStringUntil("Transferred") << "'\n";
}

注意:

  • 看起来好像你基本上都在努力避免异步电话。这让事情变得笨拙。如果您只需要超时,请参阅Boost::Asio synchronous client with timeoutboost::asio + std::future - Access violation after closing socket
  • 您似乎没有意识到*read_until可以读取超出分隔符(它将首先读取 ,包括第一次看到分隔符时)。你真的应该考虑它
  • 您永远不会检查run_one()的返回值。如果它返回0,则循环应该退出。在不执行reset()的情况下再次运行它将永远不会做任何事情。

¹为什么?