Reputation: 155
Here is my code
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;
}
}
My output is
ret = 8
Message Log, Reading /dev/ttyS0: Success
Message Log, Reading /dev/ttyS0 with data = 0066923:
I am reading only 8 bytes instead of 80.
I should receive 0066923:12:13:134:1134:112344:333...(till 80 bytes)
The output on gtkterm and I am receiving the complete data.
Upvotes: 2
Views: 258
Reputation: 1281
Its non-blocking read operation, so its possible that read will return whatever data received in the buffer at the moment.
You have to loop through the read until all data received.
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;
}
Upvotes: 0
Reputation: 70921
read()
does not necessarily return the number of bytes it was told to read.
So loop around read until you got what you want:
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;
}
....
Upvotes: 3