其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
Linux下用select查询串口数据

作者:未知 来源:月光软件站 加入时间:2005-6-5 月光软件站

       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;

}




相关文章

相关软件