[英]boost::asio blocks std::cout when reading from serial port
I'm using boost::asio
to read from a serial port. 我正在使用
boost::asio
从串行端口读取。 I continuously read from the serial port and print it out through std::cout
. 我不断从串口读取数据,并通过
std::cout
其打印出来。 But some strange things happens. 但是有些奇怪的事情发生了。
I'm using TimeoutSerial
class from here . 我从这里使用
TimeoutSerial
类。 My code goes like this: 我的代码是这样的:
#include <iostream>
#include "TimeoutSerial.h"
using namespace std;
int main(){
TimeoutSerial serial;
serial.open("/dev/ttyACM0", 9600 );
serial.setTimeout(boost::posix_time::seconds(1));
char c = '0';
while(true){
try{
serial.read( &c, 1 );
cout << c;
}catch( std::runtime_error err ){
cout << "Error: " << err.what()<< endl;
}
}
return 0;
}
I get no output and I have no idea why. 我没有输出,我也不知道为什么。 When I change
cout << c;
当我改变
cout << c;
to cout << c << endl;
cout << c << endl;
I get the output I want but each character is on a new line which is undesirable. 我得到了想要的输出,但是每个字符都在换行符上,这是不希望的。
So can anyone tell me why is this happening? 谁能告诉我为什么会这样?
std::cout
is buffered by default, so you need to flush it to display it on your terminal. std::cout
默认情况下是缓冲的,因此您需要刷新它才能在终端上显示它。 Using std::endl
does this implicitly, as will std::flush()
. 使用
std::endl
和std::flush()
都会隐式执行此操作。 Change your loop to 将循环更改为
while(true) {
try {
serial.read( &c, 1 );
cout << c;
std::flush( std::cout );
} catch ( std::runtime_error err ) {
cout << "Error: " << err.what() << endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.