com_err.c revision f404167dda29a59d2be2882328aeb074b9899669
1/*
2 * Copyright 1987, 1988 by MIT Student Information Processing Board.
3 *
4 * Permission to use, copy, modify, and distribute this software and
5 * its documentation for any purpose is hereby granted, provided that
6 * the names of M.I.T. and the M.I.T. S.I.P.B. not be used in
7 * advertising or publicity pertaining to distribution of the software
8 * without specific, written prior permission.  M.I.T. and the
9 * M.I.T. S.I.P.B. make no representations about the suitability of
10 * this software for any purpose.  It is provided "as is" without
11 * express or implied warranty.
12 */
13
14#include "config.h"
15#include <stdio.h>
16#ifdef HAVE_TERMIOS_H
17#include <termios.h>
18#endif
19#ifdef HAVE_UNISTD_H
20#include <unistd.h>
21#endif
22#include "com_err.h"
23#include "error_table.h"
24#include "internal.h"
25
26static void
27default_com_err_proc (const char *whoami, errcode_t code, const
28		      char *fmt, va_list args)
29	COM_ERR_ATTR((format(printf, 3, 0)));
30
31static void
32default_com_err_proc (const char *whoami, errcode_t code, const
33		      char *fmt, va_list args)
34{
35    int do_cr = 1, fd = fileno(stderr);
36
37    if (whoami) {
38	fputs(whoami, stderr);
39	fputs(": ", stderr);
40    }
41    if (code) {
42	fputs(error_message(code), stderr);
43	fputs(" ", stderr);
44    }
45    if (fmt) {
46        vfprintf (stderr, fmt, args);
47    }
48    if (!isatty(fd))
49	do_cr = 0;
50#ifdef HAVE_TERMIOS_H
51    else {
52	struct termios t;
53
54	if ((tcgetattr(fd, &t)) == 0 &&
55	    (t.c_oflag & OPOST) && (t.c_oflag & ONLCR))
56	do_cr = 0;
57    }
58#endif
59    if (do_cr)
60	fputc('\r', stderr);
61    fputc('\n', stderr);
62    fflush(stderr);
63}
64
65typedef void (*errf) (const char *, errcode_t, const char *, va_list);
66
67errf com_err_hook = default_com_err_proc;
68
69void com_err_va (const char *whoami, errcode_t code, const char *fmt,
70		 va_list args)
71{
72    (*com_err_hook) (whoami, code, fmt, args);
73}
74
75void com_err (const char *whoami,
76	      errcode_t code,
77	      const char *fmt, ...)
78{
79    va_list pvar;
80
81    if (!com_err_hook)
82	com_err_hook = default_com_err_proc;
83    va_start(pvar, fmt);
84    com_err_va (whoami, code, fmt, pvar);
85    va_end(pvar);
86}
87
88errf set_com_err_hook(errf new_proc)
89{
90    errf x = com_err_hook;
91
92    if (new_proc)
93	com_err_hook = new_proc;
94    else
95	com_err_hook = default_com_err_proc;
96
97    return x;
98}
99
100errf reset_com_err_hook(void) {
101    errf x = com_err_hook;
102    com_err_hook = default_com_err_proc;
103    return x;
104}
105