Achmed
Achmed

Reputation: 323

C bulk write multiple values at once

I am trying to write a bunch of values to a FIFO pipe - which works fine, but the issue that I have is that the program on the other end of the FIFO pipe, ends up reading the values before all are written (I assume kernel scheduling isn't working in my favor). Below is what my code is somewhat like (this works well - half of the time):

write(out_fd, (void *)struct_1, sizeof(struct part_1));
write(out_fd, (void *)struct_2, sizeof(struct part_2));
write(out_fd, (void *)struct_3, sizeof(struct part_3));

However - what I assume is that - kernel scheduling essentially interrupts somewhere in-between the sequential writes, whilst on the other end of the FIFO pipe, another program reads all values as they come in, and when it does not match the expected full (multiple) values being written - at once, my programs fails to operate correctly, as the values do not match the format what is expected.

Does anyone have any ideas into how all write's can be written in bulk, such as preventing scheduling from switching between applications before all write's can be done. My initial attempt was to malloc enough space for all of the values, then to memcpy the values towards a respective offset - matching each interval position - and then writing that; however, this ended up causes heap memory corruption (after freeing all), which only became present further down the line.

Any suggestions? Thank you.

Upvotes: 0

Views: 119

Answers (1)

Ture Pålsson
Ture Pålsson

Reputation: 6786

A FIFO is just a stream of bytes; it provides no framing of any kind. In particular, there is no guarantee that read() will read the same chunks that write() wrote. Fix your receiver to handle this.

Upvotes: 1

Related Questions