gpt4 book ai didi

c++ - 与设备文件的异步读写

转载 作者:行者123 更新时间:2023-11-30 03:59:57 24 4
gpt4 key购买 nike

我正在将一些二进制数据写入/dev/itun 之类的设备文件。

void ahaConnector::asyncWriteData(vector<uint8_t> packedMessage) {

cout<<"\n async write data packed message";
deviceStreamDescriptor.assign(device);
boost::asio::write (
deviceStreamDescriptor,
boost::asio::buffer(packedMessage)
);


readbuffer.resize(1024);
deviceStreamDescriptor.async_read_some(boost::asio::buffer(readbuffer),
boost::bind(&ahaConnector::readHeader, this,
boost::asio::placeholders::error(),
boost::asio::placeholders::bytes_transferred()
));
io_service.run();

}

void ahaConnector::readHeader(const boost::system::error_code &ec, std::size_t bytes_transferred) {


if(!ec) {

std::cout<<"\n Bytes transfereed :"<<bytes_transferred<<" "<<readbuffer.size();


deviceStreamDescriptor.async_read_some(boost::asio::buffer(readbuffer),
boost::bind(&ahaConnector::readHeader, this,
boost::asio::placeholders::error(),
boost::asio::placeholders::bytes_transferred()
));

Callbacks callbacks;
callbacks.OnReceivingPackedMessage();
io_service.run();

}
else {

cout<<"\n System Error Code "<<ec;
}

}

回调函数 readhandler 已成功执行,但我无法将控制从我的回调函数转移到另一个类。

从设计的角度来看是有问题的。我需要处理从回调函数收到的消息以获得进一步的逻辑。我应该在这里使用另一个线程吗?

最佳答案

查看此代码,您可能只想替换 read(device,...)通过 boost Asio 对 Posix 流的支持:

#include <boost/asio.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/function.hpp>
#include <iostream>

static int device = 0;

using namespace boost;

int main() {
boost::asio::io_service io_svc;
boost::asio::posix::stream_descriptor iodevice(io_svc, device);

char buffer[1024];
function<void(system::error_code const&, size_t)> callback;
callback = [&](boost::system::error_code const& ec, size_t bytes_transferred) {
if (ec)
{
std::cout << "Error '" << ec.message() << "' during asynchronous operation\n";
}
else
{
std::cout << "Read exactly " << bytes_transferred << " bytes\n";
std::cout << "Data: '";
std::cout.write(buffer, bytes_transferred);
std::cout << "'\n";

iodevice.async_read_some(asio::buffer(buffer), callback);
}
};

iodevice.async_read_some(asio::buffer(buffer), callback);

io_svc.run();
}

查看 Live On Coliru

遗憾的是,在 Coliru 上它无法工作,因为输入是从非流重定向的。但是,如果您以交互方式运行它,它将起作用并打印输入的前 10 个字符。

关于c++ - 与设备文件的异步读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26599108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com