为什么我的IO_Service :: run_one()的实现会导致不确定的块并触发错误#125

Why Is my implementation of io_service::run_one() causing an indefinite block and triggering error #125?

本文关键字:不确定 #125 错误 run 我的 Service one 实现 为什么 IO      更新时间:2023-10-16

我正在使用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,'');//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

首先,错误125的操作中止了:这意味着(可能(cancel((呼叫(或io对象的破坏者导致取消(。

那只是正常的。

我已经艰苦地完成了您的不完整代码¹,并且不容易看到您的问题:

活在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, ''); // 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同步客户端与超时:: asio std :: Future-未来 - 关闭插座后访问违规
  • 您似乎没有意识到*read_until可以读取以外的 至少会读取至少,直到第一次看到定界符(。您应该真正考虑
  • 您永远不要检查run_one()的返回值。如果返回0,则循环应退出。在不执行reset()的情况下再次运行它不会做任何事情。

¹为什么?

我的解决方法是:

    case resultSuccess:
        m_timer.cancel();
        m_io.reset();
        break;//go to finalize timer spirious event
        //return;