PageRenderTime 51ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/error.c

https://bitbucket.org/fedjo/parlab3
C | 82 lines | 61 code | 14 blank | 7 comment | 5 complexity | d89d7765fde23a64bbc90ef23f4780ff MD5 | raw file
  1. /*
  2. * error.c -- Error handling routines
  3. *
  4. * Copyright (C) 2010-2012, Computing Systems Laboratory (CSLab)
  5. * Copyright (C) 2010-2012, Vasileios Karakasis
  6. */
  7. #include <errno.h>
  8. #include <stdarg.h>
  9. #include <stdlib.h>
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include "error.h"
  13. #define ERRMSG_LEN 4096
  14. char *program_name = NULL;
  15. static void
  16. do_error(int use_errno, const char *fmt, va_list arg)
  17. {
  18. char errmsg[ERRMSG_LEN];
  19. *errmsg = '\0'; /* ensure initialization of errmsg */
  20. if (program_name)
  21. snprintf(errmsg, ERRMSG_LEN, "%s: ", program_name);
  22. vsnprintf(errmsg + strlen(errmsg), ERRMSG_LEN, fmt, arg);
  23. if (use_errno && errno)
  24. /* errno is set */
  25. snprintf(errmsg + strlen(errmsg), ERRMSG_LEN,
  26. ": %s", strerror(errno));
  27. strncat(errmsg, "\n", ERRMSG_LEN);
  28. fflush(stdout); /* in case stdout and stderr are the same */
  29. fputs(errmsg, stderr);
  30. fflush(NULL);
  31. return;
  32. }
  33. void
  34. set_program_name(char *path)
  35. {
  36. if (!program_name)
  37. program_name = strdup(path);
  38. if (!program_name)
  39. error(1, "strdup failed");
  40. }
  41. void
  42. warning(int use_errno, const char *fmt, ...)
  43. {
  44. va_list ap;
  45. va_start(ap, fmt);
  46. do_error(use_errno, fmt, ap);
  47. va_end(ap);
  48. return;
  49. }
  50. void
  51. error(int use_errno, const char *fmt, ...)
  52. {
  53. va_list ap;
  54. va_start(ap, fmt);
  55. do_error(use_errno, fmt, ap);
  56. va_end(ap);
  57. exit(EXIT_FAILURE);
  58. }
  59. void
  60. fatal(int use_errno, const char *fmt, ...)
  61. {
  62. va_list ap;
  63. va_start(ap, fmt);
  64. do_error(use_errno, fmt, ap);
  65. va_end(ap);
  66. abort();
  67. exit(EXIT_FAILURE); /* should not get here */
  68. }