【问题标题】:Why Is my implementation of io_service::run_one() causing an indefinite block and triggering error #125?为什么我的 io_service::run_one() 实现会导致无限期阻塞并触发错误 #125?
【发布时间】:2017-06-08 12:39:28
【问题描述】:

我正在使用 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(),我会进入一个无限循环而不是进入 switch case。

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

【问题讨论】:

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


    【解决方案1】:

    首先,错误 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() 将永远不会执行任何操作。

    ¹为什么?

    【讨论】:

    • 嘿!感谢您跟踪并帮助我!如果我向您传递了不完整的代码集,我深表歉意。这是原始的sn-p。我在控制台上收到“阅读时出错”。在这种情况下, io.run_one() 执行了什么? result = resultInProgress 是如何改变它的值的?对于那些将来会关注的人,这是question的延续@
    • 你试过调试吗?或者在readCompletedtimeoutExpired 处理程序中添加一些跟踪?如您所见,我是not getting the specific behaviour。请务必注意我的答案代码下方的所有注释。
    • 我会尝试调试它。设置 SublimeGDB 和项目文件/设置真的很混乱,但我会坚持下去。非常感谢您的帮助
    • 这些工具会让您终生珍惜。祝你好运
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2018-11-15
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多