views:

45

answers:

0

I'm trying to create a C++ serial port class for a project that i'm working on. Unfortunately I'm stuck. I need the user to be able to specify if the port read function is blocking or non-blocking. So when the user creates a port object they specify a flags variable. If flags is set then the read should return -1 if there is no data at the port. If flags is not set then the read should wait until data is available and then return the count of characters. Here is part of my code:

fd = open(port, O_RDWR | O_NOCTTY);
termios port_settings ;
if ( tcgetattr( fd, &port_settings ) < 0 )
{
  cout << "Error getting settings" << endl;
}
//                                                                                                                                                        
// Set the baud rate for both input and output.                                                                                                           
//                                                                                                                                                        
if ( ( cfsetispeed( &port_settings, baud ) < 0 )
     || ( cfsetospeed( &port_settings, baud ) < 0 ) )
{
  cout << "Error setting settings" << endl;
}
//                                                                                                                                                        
//Set Blocking/Non-Blocking                                                                                                                               
//                                                                                                                                                        
if( flags )
{
  fcntl(fd, F_SETFL, FNDELAY); //set non-blocking read                                                                                                    
}
else
{
  flags = fcntl(fd, F_GETFL);
  flags &= ~O_NONBLOCK;
  fcntl(fd, F_SETFL, flags);

  //fcntl(fd, F_SETFL, 0);    //set blocking read                                                                                                         
  port_settings.c_cc[VTIME]    = 0;   /* inter-character timer unused */
  port_settings.c_cc[VMIN]     = 1;   /* blocking read until 5 chars received */

  tcflush(fd, TCIFLUSH);
}
//                                                                                                                                                        
// Set the new attributes of the serial port.                                                                                                             
//
if ( tcsetattr( fd, TCSANOW, &port_settings ) < 0 )
{
  cout << "Error applying settings" << endl;
}

Currently the program always returns 0 immediately.

Any suggestions would be greatly appreciated.