如何使用asio与设备文件
how to use asio with device files
我在整个项目中使用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));
}
}
问题是,我使用async_read没有任何完整的条件。因此,永远不会调用回调。在更改对async_read_some的调用后,一切都如预期的那样工作。
相关文章:
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 如何在其他文件中使用函数
- 在实现文件中使用头文件的通用 lambda
- 将 getline() 与文件一起使用
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 定义C++新的环境变量并在 bat 文件中使用它
- 如何在另一个 CPP 文件中使用一个 cpp 文件中的函数?
- 在 embarcadero / RAD 工作室中的 .dfm 文件中使用常量
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- 如何在 linux 可执行文件中使用静态库
- 在C++的头文件中使用常量并在程序中询问其地址的任何潜在危险
- 使用 libssh 从 SFTP 服务器下载文件并使用 C++ 将其写入 ofstream?
- CocoaPod - 在头文件中使用 C++ 时出现 Podspec 检查错误
- 链接器输入文件未使用,因为链接未完成,我无法获得.o
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 如何为文件路径使用变量?
- 没有头文件如何使用c ++调用其他模块中的函数?
- 在带有类型保护的模板文件中使用前向声明
- 无法使包含.hpp文件与其中的2个文件一起使用
- 文件删除(使用取消链接)与释放所有磁盘空间之间的延迟