tuklib_exit.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. ///////////////////////////////////////////////////////////////////////////////
  2. //
  3. /// \file tuklib_exit.c
  4. /// \brief Close stdout and stderr, and exit
  5. //
  6. // Author: Lasse Collin
  7. //
  8. // This file has been put into the public domain.
  9. // You can do whatever you want with this file.
  10. //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "tuklib_common.h"
  13. #include <stdlib.h>
  14. #include <stdio.h>
  15. #include "tuklib_gettext.h"
  16. #include "tuklib_progname.h"
  17. #include "tuklib_exit.h"
  18. extern void
  19. tuklib_exit(int status, int err_status, int show_error)
  20. {
  21. if (status != err_status) {
  22. // Close stdout. If something goes wrong,
  23. // print an error message to stderr.
  24. const int ferror_err = ferror(stdout);
  25. const int fclose_err = fclose(stdout);
  26. if (ferror_err || fclose_err) {
  27. status = err_status;
  28. // If it was fclose() that failed, we have the reason
  29. // in errno. If only ferror() indicated an error,
  30. // we have no idea what the reason was.
  31. if (show_error)
  32. fprintf(stderr, "%s: %s: %s\n", progname,
  33. _("Writing to standard "
  34. "output failed"),
  35. fclose_err ? strerror(errno)
  36. : _("Unknown error"));
  37. }
  38. }
  39. if (status != err_status) {
  40. // Close stderr. If something goes wrong, there's
  41. // nothing where we could print an error message.
  42. // Just set the exit status.
  43. const int ferror_err = ferror(stderr);
  44. const int fclose_err = fclose(stderr);
  45. if (fclose_err || ferror_err)
  46. status = err_status;
  47. }
  48. exit(status);
  49. }