Read()函数不读取串行通信的全部数据

时间:2013-11-19 06:10:01

标签: c linux-device-driver

这是我的代码

void Reading_TtyS0()
{
     int ret;
     char mypipe_ttyS0[80] = {0};
     fcntl(fd, F_SETFL, 0);

     ret = read(fd, ttyS0_mypipe , 80 );
     printf(ret = %d\n", ret);
     if (ret > 0)
     {
         perror("Message Log, Reading /dev/ttyS0");
         printf("Message Log, Reading /dev/ttyS0 with data = %s\n",  ttyS0_mypipe);
         tcflush(fd, TCIFLUSH);
         ret = 0;
     }
}

我的输出是

ret = 8

消息日志,读取/ dev / ttyS0:成功

消息日志,读取/ dev / ttyS0,数据= 0066923:

我只读取8个字节而不是80个字节。

我应该收到0066923:12:13:134:1134:112344:333 ......(直到80字节)

gtkterm上的输出,我收到了完整的数据。

2 个答案:

答案 0 :(得分:3)

read()不一定返回被告知要读取的字节数。

所以循环阅读,直到你得到你想要的东西:

 char mypipe_ttyS0[80] = {0};
 fcntl(fd, F_SETFL, 0);

 size_t bytes_to_read = 80;
 size_t bytes_read = 0;
 while (bytes_to_read > 0)
 {
   ssize_t result = read(fd, ttyS0_mypipe + bytes_read, bytes_to_read);
   if (-1 == result)
   {
     if ((EWOULDBLOCK == errno) || (EAGAIN == errno))
     {
       continue;
     }

     perror("read() failed");

     break;
   } 
   else (0 == result)
   {
     fprintf(stderr, "Connection closed.");

     break;
   }

   printf("Read %zd bytes.\n", result);

   bytes_to_read -= result;
   bytes_read += result;
 }

 ....

答案 1 :(得分:0)

它的非阻塞读取操作,因此读取可能会返回缓冲区中接收到的任何数据。

您必须循环读取,直到收到所有数据。

 int ret;
 char mypipe_ttyS0[80] = {0};
 fcntl(fd, F_SETFL, 0);

 int i = 5; // let say iterate 5 times
 int bytes_to_read = 80;
 ret = 0;
 while (i > 0)
 {
    ret += read(fd, mypipe_ttyS0 + ret , bytes_to_read );
    printf(ret = %d\n", ret);

    bytes_to_read -= ret;
    if(bytes_to_read == 0)
    {
         break;
    } 
    ++i;
 }

    if (bytes_to_read == 0)
    {
         perror("Message Log, Reading /dev/ttyS0");
         printf("Message Log, Reading /dev/ttyS0 with data = %s\n",  ttyS0_mypipe);
         tcflush(fd, TCIFLUSH);
         ret = 0;
    }