| 1 | #include <errno.h> |
| 2 | #include <stdarg.h> |
| 3 | #include <stdio.h> |
| 4 | #include <stdlib.h> |
| 5 | #include <string.h> |
| 6 | |
| 7 | #include "warnp.h" |
| 8 | |
| 9 | static int initialized = 0; |
| 10 | static char * name = NULL; |
| 11 | |
| 12 | /* Free the name string. */ |
| 13 | static void |
| 14 | done(void) |
| 15 | { |
| 16 | |
| 17 | free(name); |
| 18 | name = NULL; |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * warnp_setprogname(progname): |
| 23 | * Set the program name to be used by warn() and warnx() to ${progname}. |
| 24 | */ |
| 25 | void |
| 26 | warnp_setprogname(const char * progname) |
| 27 | { |
| 28 | const char * p; |
| 29 | |
| 30 | /* Free the name if we already have one. */ |
| 31 | free(name); |
| 32 | |
| 33 | /* Find the last segment of the program name. */ |
| 34 | for (p = progname; progname[0] != '\0'; progname++) |
| 35 | if (progname[0] == '/') |
| 36 | p = progname + 1; |
| 37 | |
| 38 | /* Copy the name string. */ |
| 39 | name = strdup(p); |
| 40 | |
| 41 | /* If we haven't already done so, register our exit handler. */ |
| 42 | if (initialized == 0) { |
| 43 | atexit(done); |
| 44 | initialized = 1; |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | void |
| 49 | warn(const char * fmt, ...) |
| 50 | { |
| 51 | va_list ap; |
| 52 | |
| 53 | va_start(ap, fmt); |
| 54 | fprintf(stderr, "%s", (name != NULL) ? name : "(unknown)"); |
| 55 | if (fmt != NULL) { |
| 56 | fprintf(stderr, ": "); |
| 57 | vfprintf(stderr, fmt, ap); |
| 58 | } |
| 59 | fprintf(stderr, ": %s\n", strerror(errno)); |
| 60 | va_end(ap); |
| 61 | } |
| 62 | |
| 63 | void |
| 64 | warnx(const char * fmt, ...) |
| 65 | { |
| 66 | va_list ap; |
| 67 | |
| 68 | va_start(ap, fmt); |
| 69 | fprintf(stderr, "%s", (name != NULL) ? name : "(unknown)"); |
| 70 | if (fmt != NULL) { |
| 71 | fprintf(stderr, ": "); |
| 72 | vfprintf(stderr, fmt, ap); |
| 73 | } |
| 74 | fprintf(stderr, "\n"); |
| 75 | va_end(ap); |
| 76 | } |