recently, after writing a PLC communication protocol, I sent it a command to read 1 byte after the address 0x0000 (the address 0x0000 exists in PLC, and sent successfully, and the data sent is correct), it should send me 12 bytes (including ACK, site number, error code, etc.).
but I tested it many times, and it only replied me with 1 or 2 bytes of data, and the next time I sent the same read instruction, it gave me the next 11 or 10 bytes of data.
then I used the serial debugging tool to send it only once and received all 12 bytes without error. So at that time, I wondered if the code had a problem with the encapsulation of read_n, and then I debugged it and sent it. After receiving the 1 or 2 bytes, the next read returned 0 (Connection timed out). Errno directly and was set to 110 errno
.ssize_t ha_read_n(int fd, void *buf, size_t count)
{
size_t nleft = count;
ssize_t nread;
char *bufp = (char*) buf;
while (nleft > 0)
{
if ((nread = read(fd, bufp, nleft)) < 0)
{
if (errno == EINTR)
{
//printf("read_n: nread = %d, errno = EINTR(%d)\n", (int)nread, errno);
continue;
}
return -1;
}
else if (nread == 0)
{
//printf("read_n: nread = 0, errno = %d\n", errno);
// , errno == 110
return count - nleft;
}
bufp += nread;
nleft -= nread;
}
return count;
}
does anyone encounter this situation, or are there any flaws in my code?