プロジェクト全体でboostasioを使用しています。デバイスファイル()を読みたいと思います/dev/input/eventX
。Boost asioのドキュメントには、通常のファイルIOは不可能であると記載されていますが、デバイスファイルまたはパイプはasio::posix::stream_descriptor.
openを介してファイル記述子を開き、stream_descriptorに割り当てました。私は今、async_read()
二度と戻らない電話をかけます。
入力イベントでboostasioを使用することは可能ですか?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));
}
}