Skip to content

Instantly share code, notes, and snippets.

@mrPjer
Last active August 29, 2015 14:18
Show Gist options
  • Save mrPjer/3dfcdea1c362b5446f95 to your computer and use it in GitHub Desktop.
Save mrPjer/3dfcdea1c362b5446f95 to your computer and use it in GitHub Desktop.
Why won't my program output when redirected to a file?

The problem

  • Output not being output when redirecting output to a file

The cause

  • When stdout points to a file, it gets buffered by libc into a 4k buffer
  • Terminal output is line buffered, stderr is always unbuffered

The fix

  • fflush in the program - what if we don't have the source?
  • stdbuf -oL command - forces line buffering mode
  • unbuffer command - part of expect, runs the command in a pty

See more

#include <stdio.h>
#include <unistd.h>
int main() {
for(int i = 0;; ++i) {
printf("%d\n", i);
fflush(stdout);
sleep(1);
}
}
#include <stdio.h>
#include <unistd.h>
int main() {
for(int i = 0;; ++i) {
printf("%d\n", i);
sleep(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment