我正在尝试使用 boost asio async_read 在 while 循环内以非阻塞方式捕获单个键盘输入。处理程序应显示读取的字符。
我的代码:
#include <boost/asio/io_service.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/asio/read.hpp>
#include <boost/system/error_code.hpp>
#include <iostream>
#include <unistd.h>
#include <termios.h>
using namespace boost::asio;
void read_handler(const boost::system::error_code&, std::size_t)
{
char c;
std::cin>>c;
std::cout << "keyinput=" << c << std::endl;
}
int main()
{
io_service ioservice;
posix::stream_descriptor stream(ioservice, STDIN_FILENO);
char buf[1];
while(1)
{
async_read(stream, buffer(buf,sizeof(buf)), read_handler);
ioservice.run();
}
return 0;
}
我的输出不符合预期(keyinput=char 格式):
a
key input
b
c
d
e
我哪里错了?
此外,该程序非常占用 CPU。如何纠正?
最佳答案
对于标准输入的异步 IO 有一个重要的限制:Strange exception throw - assign: Operation not permitted
其次,如果您使用async_read
,请不要同时使用std::cin
(您只会进行两次读取)。 (请改为查看 async_wait)。
除此之外,您应该能够通过正确使用异步 IO 来解决高 CPU 负载问题:
#include <boost/asio.hpp>
#include <iostream>
using namespace boost::asio;
int main()
{
io_service ioservice;
posix::stream_descriptor stream(ioservice, STDIN_FILENO);
char buf[1] = {};
std::function<void(boost::system::error_code, size_t)> read_handler;
read_handler = [&](boost::system::error_code ec, size_t len) {
if (ec) {
std::cerr << "exit with " << ec.message() << std::endl;
} else {
if (len == 1) {
std::cout << "keyinput=" << buf[0] << std::endl;
}
async_read(stream, buffer(buf), read_handler);
}
};
async_read(stream, buffer(buf), read_handler);
ioservice.run();
}
如您所见,while
循环已替换为一系列异步操作。
关于c++ - 使用 boost async_read 和 posix::stream_descriptor 从键盘读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52308998/