如何使用asio与设备文件

how to use asio with device files

本文关键字:文件 何使用 asio      更新时间:2023-10-16

我在整个项目中使用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的调用后,一切都如预期的那样工作。