0

我有以下代码从 RS232 端口读取数据。对于某些(从头开始)运行,io.run()立即返回并按m_handler()预期调用。但有时(从头开始重新运行),io.run()即使是第一次在 while 循环内调用,也会进入一个内部永远循环(永远堆叠在里面)。这是随机发生的。这里的潜在问题是什么?

#define BUF_SIZE    512
char data[BUF_SIZE];

void my_handler(const boost::system::error_code& err, std::size_t bytes_transferred)
{
printf("%d\n", bytes_transferred);
if (!err){
   process_data();
}
}


void test_serial_port( int argc, char* argv[]  )
{
// hard coded parameters
const char *PORT = "COM1";
serial_port_base::baud_rate BAUD(9600);
serial_port_base::character_size CSIZE( 8 );
serial_port_base::flow_control FLOW( serial_port_base::flow_control::software );
serial_port_base::parity PARITY( serial_port_base::parity::none );
serial_port_base::stop_bits STOP( serial_port_base::stop_bits::one );

io_service io;
serial_port port( io, PORT );


// go through and set all the options as we need them
// all of them are listed, but the default values work for most cases
port.set_option( BAUD );
port.set_option( CSIZE );
port.set_option( FLOW );
port.set_option( PARITY );
port.set_option( STOP );

while( !kbhit() )
{
    io.reset();

    port.async_read_some( 
        boost::asio::buffer(data, BUF_SIZE), 
        boost::bind(&my_handler, boost::asio::placeholders::error,
                    boost::asio::placeholders::bytes_transferred )
        );

    io.run();

    Sleep(300);
}
}
4

0 回答 0