Dav*_*rle 8 c++ linux boost boost-asio
我在整个项目中都使用了boost asio.我现在想要读取一个设备文件(/dev/input/eventX).在boost asio文档中,它声明不能使用普通文件IO,但使用支持设备文件或管道asio::posix::stream_descriptor.
我通过open打开文件描述符并将其分配给stream_descriptor.我现在发出一个async_read()永不回复的电话.
是否可以在输入事件中使用boost asio?在通过ioctl与asio一起使用之前,是否需要配置文件句柄?
编辑:添加一些示例代码 - >添加了一些示例代码.
以下代码打开/ dev/input/event12,并调用io_service对象上的run方法.
#include <boost/asio.hpp>
#include <string>
#include <iostream>
#include <boost/bind.hpp>
#include <linux/input.h>
namespace asio = boost::asio;
#ifdef BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR
typedef asio::posix::stream_descriptor stream_descriptor;
#else // BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR
typedef asio::windows::stream_handle stream_descriptor;
#endif // BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR
class FileReader
{
typedef boost::shared_ptr<asio::streambuf> StreambufPtr;
typedef boost::shared_ptr<FileReader> FileReaderPtr;
typedef boost::weak_ptr<FileReader> FileReaderWeakPtr;
public:
static FileReaderWeakPtr Create(asio::io_service& io_service, const std::string& path);
virtual ~FileReader();
void HandleRead(FileReaderPtr me, StreambufPtr sb,
const boost::system::error_code &error);
private:
FileReader(asio::io_service& io_service, const std::string& path);
stream_descriptor m_InputStream;
};
FileReader::FileReaderWeakPtr FileReader::Create(asio::io_service& io_service,
const std::string& path){
FileReaderPtr ptr(new FileReader(io_service, path));
StreambufPtr sb(new boost::asio::streambuf());
asio::async_read(ptr->m_InputStream, *sb,
boost::bind(&FileReader::HandleRead, ptr.get(),
ptr, sb, asio::placeholders::error));
return ptr;
}
FileReader::FileReader(asio::io_service& io_service, const std::string& path)
:m_InputStream(io_service)
{
int dev = open(path.c_str(), O_RDONLY);
if (dev == -1) {
throw std::runtime_error("failed to open device " + path);
}
m_InputStream.assign(dev);
}
void FileReader::HandleRead(FileReaderPtr me, StreambufPtr sb,
const boost::system::error_code &error) {
if(!error) {
//Inform all of a sucessfull read
std::istream is(sb.get());
size_t data_length = sb->size();
asio::async_read(m_InputStream, *sb,
boost::bind(&FileReader::HandleRead, this, me, sb, asio::placeholders::error));
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我在没有任何完整条件的情况下使用 async_read 。因此回调从未被调用。更改对 async_read_some 的调用后,一切都按预期工作。