clinuxiointel-edison

output file redirection (almost) never works with my c program in linux


If I type myprogram > file I end up with a file of size 0 except for one time when it worked. Same program, no changes between times when it worked and when it didn't. Without the redirection it prints out to the terminal just fine. Virtually all the online help assumes you are needing to redirect std error but that is not the case here.

The program is multi threaded and reads a USB port and writes it out to a bluetooth port. There is not keyboard input and no exit, it just runs. I stop it with ctrl-c. This is embedded code on a headless linux Intel Edison.

I assume I need to do something in the code to allow for the redirection. It is probably something simple I should know but I don't. I would appreciate some help.


Solution

  • When you redirect to a file, libc will automatically buffer your data.

    Since you kill your script instead of exiting gracefully, you stop the process before it writes the buffer out.

    You can use fflush(stdout); to write out (aka flush) the current buffer at any time.

    You can use setvbuf(stdout, NULL, _IONBF, 0); to disable stdout buffering all together.