tom
tom

Reputation: 1590

boost::asio blocks std::cout when reading from serial port

I'm using boost::asio to read from a serial port. I continuously read from the serial port and print it out through std::cout. But some strange things happens.

I'm using TimeoutSerial class from here. 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; to 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?

Upvotes: 0

Views: 731

Answers (1)

Sam Miller
Sam Miller

Reputation: 24164

std::cout is buffered by default, so you need to flush it to display it on your terminal. Using std::endl does this implicitly, as will 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;
    }
}      

Upvotes: 1

Related Questions