Emulating line-buffering mode (Gradle example)

C printf() function doesn't flush buffers by default, and a lot of code using it may miss this, therefore creating interactivity problems to the end user. It's not specific to C though - it's about the standard I/O streams, and the problem may appear anywhere. The post is based on StackExchange discussion, so you can dig deeper if you want: Turn off buffering in pipe.

Example is based on C code that is specific for macos and has the functionality to read connected USB devices and wait for the specific one.

The Gradle script contains two tasks - runSimple task that runs the program naively, and run task that using "script" utility to emulate the line-buffering mode.

If you use runSimple, then there will be no output until the device is actually connected (and no output at all if you use Ctrl-C to break the execution):

~/ > gradle runSimple
Starting a Gradle Daemon, 1 busy Daemon could not be reused, use --status for details
:compile UP-TO-DATE
Waiting for Cruzer
Got 4 connected devices. Still waiting...
Got 4 connected devices. Still waiting...


Total time: 7.851 secs

However, run works correctly and shows the output as needed. The best solution though would be using fflush() function, but unfortunately it's not always possible (especially if we use 3rd party program that we can't recompile).


Popular posts from this blog

DIY: Business cards in LaTeX

Python vs JS vs PHP for embedded systems

Web application framework comparison by memory consumption