我正在创建在Windows和Linux上均可使用的串行端口库。因此,我选择了Boost作为跨平台lib。我已经成功创建了图书馆。 现在,当我将此库与现有项目集成时,我遇到了以下问题。
应用程序多次打开和关闭串行端口,在Linux中我的库运行流畅,多次打开和关闭都没有问题。当我在Windows中相同运行时,多个打开关闭开始引发访问被拒绝的消息。
在Linux中,上述问题不存在
开放代码
bool SerialPort::ComOpen(char *com_port_name, int nBaudrate, parity /*nParity*/, stop_bits /*nStopBits*/, flow_control /*nDataBits*/){
boost::system::error_code error_code;
if (m_port)
{
std::cout << "error : port is already opened..." << std::endl;
return false;
}
try
{
m_port = serial_port_ptr(new boost::asio::serial_port(m_io_service));
if (m_port)
{
m_port->open(com_port_name, error_code);
}
else
{
std::cout << "serial_port_ptr : Port creation failed " << std::endl;
return false;
}
}
catch (...)
{
std::clog << boost::current_exception_diagnostic_information() << std::endl;
}
if (error_code)
{
std::cout << "error : m_port->open() failed : com_port_name = " << com_port_name << " : message : " << error_code.message() << std::endl;
return false;
}
// option settings...
m_port->set_option(boost::asio::serial_port_base::baud_rate(nBaudrate));
m_port->set_option(boost::asio::serial_port_base::character_size(8));
m_port->set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one));
m_port->set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none));
m_port->set_option(boost::asio::serial_port_base::flow_control(boost::asio::serial_port_base::flow_control::hardware));
boost::thread t(boost::bind(&boost::asio::io_service::run, &m_io_service));
m_native_file_handle = m_port->native_handle();
async_read_some_();
return true;}
关闭代码
void SerialPort::ComClose(){
boost::mutex::scoped_lock lock(m_serial_mutex);
boost::system::error_code error_code_cancel , error_code_close;
try
{
if (m_port)
{
m_port->cancel(error_code_cancel);
if (error_code_cancel)
{
std::cout << "error : m_port->cancel() failed " << error_code_cancel.message() << std::endl;
}
m_port->close(error_code_close);
if (error_code_close)
{
std::cout << "error : m_port->close() failed " << error_code_close.message() << std::endl;
}
m_port.reset();
m_io_service.stop();
m_io_service.reset();
m_port = NULL;
}
}
catch (...)
{
std::clog << boost::current_exception_diagnostic_information() << std::endl;
}
}