c++ 为什么我的io_service::run_one()的实现会导致不确定的阻塞并触发错误#125?

nzkunb0c  于 2023-06-07  发布在  其他
关注(0)|答案(2)|浏览(299)

我正在使用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

2o7dmzc5

2o7dmzc51#

首先,错误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 timeout和boost::asio + std::future - Access violation after closing socket
  • 你似乎没有意识到*read_until可以读取 * 超出 * 分隔符(它将读取 * 至少 * 直到并包括第一次看到分隔符)。你真的应该解释一下
  • 您永远不会检查run_one()的返回值。如果返回0,则循环应该退出。不执行reset()而再次运行它将不会有任何效果。

为什么?

vuktfyat

vuktfyat2#

我的解决方法是:

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

相关问题