5 * Some commonly used functions
22 #include <sys/types.h>
26 static char *perr_prog_name = NULL;
29 * perr_func: Main error reporting function
31 void perr_func(enum perr_type type, int want_errno, char *fmt, ...)
35 int err_number = errno; /* We need errno NOW */
36 char buf[PERR_BUF_SIZE], errbuf[PERR_BUF_SIZE], timebuf[PERR_BUF_SIZE];
37 char *t = NULL, *p = buf;
41 case PFE: t = "Fatal error"; break;
42 case PE: t = "Error"; break;
43 case PW: t = "Warning"; break;
44 case PI: t = "Info"; break;
45 case PD: t = "Debug"; break;
46 default: raise(SIGABRT);
48 if (!perr_prog_name) {
49 perr_prog_name = "Internal perr error";
50 perr(1, 0, "init_perr has not been called");
54 ctime_r(&timeval, timebuf);
55 *strchr(timebuf, '\n') = '\0';
57 p += sprintf(p, "%s: %s: ", perr_prog_name, t);
58 p += sprintf(p, "Thread %lu, PID %lu\n\t",
59 (unsigned long)pthread_self(), (unsigned long)getpid());
61 p += sprintf(p, "%s (%ld):\n\t", timebuf, timeval);
63 p += vsprintf(p, fmt, ap);
64 p += sprintf(p, "\n");
67 /* Print last error returned from system call */
68 p += sprintf(p, "\tErrno was: %d - %s\n",
69 err_number, strerror_r(err_number, errbuf, PERR_BUF_SIZE));
72 * Output the buffer to stderr with a single call to fprintf,
73 * which is thread-safe and locks the stderr semaphore
75 fprintf(stderr, "%s", buf);
83 void init_perr(char *prog_name)
85 perr_prog_name = prog_name;
89 * Adapted from FreeBSD source:
91 * Appends src to string dst of size siz (unlike strncat, siz is the
92 * full size of dst, not space left). At most siz-1 characters
93 * will be copied. Always NUL terminates (unless siz <= strlen(dst)).
94 * Returns strlen(src) + MIN(siz, strlen(initial dst)).
95 * If retval >= siz, truncation occurred.
97 size_t strlcat(char *dst, const char *src, size_t siz)
104 /* Find the end of dst and adjust bytes left but don't go past end */
105 while (n-- != 0 && *d != '\0')
111 return(dlen + strlen(s));
121 return (dlen + (s - src)); /* count does not include NUL */
125 * Adapted from FreeBSD source:
127 * Copy src to string dst of size siz. At most siz-1 characters
128 * will be copied. Always NUL terminates (unless siz == 0).
129 * Returns strlen(src); if retval >= siz, truncation occurred.
131 size_t strlcpy(char *dst, const char *src, size_t siz)
137 /* Copy as many bytes as will fit */
138 if (n != 0 && --n != 0) {
140 if ((*d++ = *s++) == 0)
145 /* Not enough room in dst, add NUL and traverse rest of src */
148 *d = '\0'; /* NUL-terminate dst */
153 return (s - src - 1); /* count does not include NUL */