Monday, May 11, 2020

stdio - to buffer or not to buffer?


In my previous post, I showed how stdio could be redirected to send printf() output to an available USART. It was a basic implementation designed to get things moving, but you may encounter a little quirk when sending strings that don't end with a newline '\n' character.
By default, stdio buffers (holds onto) outgoing data until it sees a newline character; at which point it sends the entire line (to the serial port). The benefit of this is that it reduces the amount of low level interactions you need to have with the USART driver code, but the disadvantage is that you have to ensure each printf() call ends with a newline if you want the string to be immediately presented to the COM port.
I'll leave it up to you as to which implementation is best for your situation, but in case you decide to eliminate the input and output buffering, here's how to do it in C.
Somewhere in your initialization code, add the following lines:
setbuf(stdout, NULL);
setbuf(stderr, NULL);
setvbuf(stdin, NULL, _IONBF, 0);
The first line will remove buffering from stdout (which is where printf() goes by default)
The second line will remove buffering from stderr (if you are using that for directing error information)
The last line will remove buffering from stdin - which is the default for where scanf() will look for input.

The juicy details can be found here:
https://www.gnu.org/software/libc/manual/html_node/Controlling-Buffering.html


3 comments:

  1. Thank you for finding the time to debate this, Personally i think strongly over it and love learning read more about this topic. Whenever possible, when you gain expertise, could you mind updating your blog with extra information? It is very great for me. 먹튀

    ReplyDelete
    Replies
    1. Thanks... if this Covid-19 lockdown goes on for much longer, I expect I'll have many more posts to make :)

      Delete
  2. This comment has been removed by a blog administrator.

    ReplyDelete