stdiobufhack.c 928 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /* Simple LD_PRELOAD library to force stdout/stderr into line-buffered mode.
  2. * This file is released to the Public Domain. */
  3. #define _GNU_SOURCE
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <dlfcn.h>
  7. #define TARGET_MODE _IOLBF
  8. static int (*libc_setvbuf)(FILE *stream, char *buf, int mode, size_t size);
  9. static int in_stdiobufhack;
  10. int setvbuf(FILE *stream, char *buf, int mode, size_t size)
  11. {
  12. if (in_stdiobufhack)
  13. return 0;
  14. in_stdiobufhack = 1;
  15. if (!libc_setvbuf)
  16. libc_setvbuf = dlsym(RTLD_NEXT, "setvbuf");
  17. if (!libc_setvbuf) {
  18. fprintf(stderr, "stdiobufhack: Did not find libc setvbuf()\n");
  19. exit(1);
  20. }
  21. if (stream == stdout || stream == stderr)
  22. mode = TARGET_MODE;
  23. in_stdiobufhack = 0;
  24. return libc_setvbuf(stream, buf, mode, size);
  25. }
  26. static void __attribute__((__constructor__)) stdiobufhack_ctor(void)
  27. {
  28. setvbuf(stdout, NULL, TARGET_MODE, 1024);
  29. setvbuf(stderr, NULL, TARGET_MODE, 1024);
  30. }