Linux下直接用read读串口可能会造成堵塞,或数据读出错误。然而用select先查询com口,再用read去读就可以避免,并且当com口延时时,程序可以退出,这样就不至于由于com口堵塞,程序就死了。我的代码如下:
bool ReadDevice( int hComm, unsigned long uLen, char* pData )
{
int nread = 0;
char inbuf[uLen];
char buff[uLen];
memset( inbuff, '\0', uLen );
memset( buff, '\0', uLen );
fd_set readset;
struct timeval tv;
int MaxFd = 0;
int c = 0;
int z;
do
{
FD_ZERO( &readset );
if( hComm >= 0 )
FD_SET( hComm, &readset );
MaxFd = hComm + 1;
tv.tv_sec = 0;
tv.tv_usec = 500000;
do
{
z = select( MaxFd, &readset, 0, 0, &tv);
}while( z==-1 && errno==EINTR );
if( z == -1 )
printf("select(2)\n");
if( z == 0 )
{
hComm = -1;
}
if( hComm>=0 && FD_ISSET(hComm, &readset) )
{
z = read( hComm, buff, uLen - c );
c += z;
if( z == -1 )
{
hComm = -1;
}
if( z > 0 )
{
buff[ z + 1 ] = '\0';
strcat( inbuff, buff );
memset( buff, 0x00, uLen );
}
else
{
hComm = -1;
}
}
}while( hComm >= 0 );
memcpy( pData, inbuff, c );
return true;
}