I have some c code that reads from a serial port into a buffer continiously and when it has read 100 bytes it writes them over a websocket using the function log_write()
.
Some of the data is missing so I think I'm getting undefined behaviour. Is there anything obviously wrong with the code?
Specifcally on the lines below should I be adding a 1 to rdlentotal
? Is it overwriting the last char of the previous read?
Also should I be null terminating the buffer after the last char that is read? How would I do this?
rdlen = read(fd_joule, &ibuf[rdlentotal], sizeof(ibuf));
rdlentotal += rdlen; /*keep track of total bytes read*/
int rdlen=0, rdlentotal = 0;
char ibuf[1024];
memset(&ibuf[0], 0, sizeof(ibuf)); /*clear the buffer*/
while (1) {
/*read from serial port*/
rdlen = read(fd_joule, &ibuf[rdlentotal], sizeof(ibuf));
rdlentotal += rdlen; /*keep track of total bytes read*/
if (rdlentotal > 100) { /*when you have 200 bytes write the websocket*/
log_write("%s", &ibuf); /*write to websocket*/
memset(&ibuf[0], 0, sizeof(ibuf)); /*clear buffer*/
rdlentotal = 0; /*rest byte counter */
rdlen = 0;
}
if (rdlen < 0) {
fprintf(stderr, "rdlen les than 0\r\n");
}
}
Updated code suggestions from Chux:
static void *serial_logging_thread() {
ssize_t rdlen = 0, rdlentotal = 0;
char ibuf[1024 + 1];
memset(&ibuf[0], 0, sizeof(ibuf)); /*clear the buffer*/
while (1) {
/*read from serial port write to log file*/
rdlen = read(fd_joule, &ibuf[rdlentotal], sizeof(ibuf) - 1 - rdlentotal);
rdlentotal += rdlen;
if (rdlentotal > 200) { /*when you have 200 bytes write to file and websocket*/
ibuf[rdlentotal + 1] = '\0'; /*null terminate*/
log_write("%s", &ibuf); /*write to websocket*/
memset(&ibuf[0], 0, sizeof(ibuf)); /*clear buffer*/
rdlentotal = 0; /*rest byte counter */
rdlen = 0;
}
if (rdlen < 0) {
LOG("error reading serial port, rdlen less than 0\r\n");
}
}
}
Declaration for log_write()
.
int log_write(const char *fmt, ... /* arguments */){
read(fd_joule, &ibuf[rdlentotal], sizeof(ibuf));
-->read(fd_joule, &ibuf[rdlentotal], sizeof(ibuf) - rdlentotal);
– chux - Reinstate Monica