-
+ 347F7CC6CC2D4AE711BAFCD7E08FEC2D76F741562B452CC8EEFBDAB6EE2A14781D162E4C4B597D528FD29D3F8295675A3636E0CB0C7F432778E56E79B1786A89
vtools/lib/error.c
(0 . 0)(1 . 78)
656 /* Written by David MacKenzie <djm@gnu.ai.mit.edu>. */
657
658 #include "system.h"
659 #include "error.h"
660 #include "progname.h"
661 #include <stdarg.h>
662 #include <stdio.h>
663 #include <stdlib.h>
664 #include <string.h>
665 #include <fcntl.h>
666
667 /* If |NULL|, error will flush |stdout|, then print on |stderr| the
668 program name, a colon and a space. Otherwise, error will call this
669 function without parameters instead. */
670 void (*error_print_progname)(void);
671
672 /* This variable is incremented each time |error| is called. */
673 unsigned int error_message_count;
674
675
676 /* Return non-zero if |fd| is open. */
677 static int
678 is_open(int fd) {
679 return 0 <= fcntl(fd, F_GETFL);
680 }
681
682 static void
683 flush_stdout(void) {
684 if (is_open(1))
685 fflush(stdout);
686 }
687
688 static void
689 print_errno_message(int errnum) {
690 char const *s;
691 char errbuf[1024];
692 if (strerror_r(errnum, errbuf, sizeof errbuf) == 0)
693 s = errbuf;
694 else
695 s = 0;
696 if (!s)
697 s = "Unknown system error";
698 fprintf(stderr, ": %s", s);
699 }
700
701 static void
702 error_tail(int status, int errnum, const char *message, va_list args) {
703 vfprintf(stderr, message, args);
704 va_end (args);
705
706 ++error_message_count;
707 if (errnum)
708 print_errno_message(errnum);
709 putc ('\n', stderr);
710 fflush(stderr);
711 if (status)
712 exit(status);
713 }
714
715
716 /* Print the program name and error message |message|, which is a
717 printf-style format string with optional args. If |errnum| is
718 nonzero, print its corresponding system error message. Exit with
719 status |status| if it is nonzero. */
720 void
721 error(int status, int errnum, const char *message, ...) {
722 va_list args;
723 flush_stdout();
724 if (error_print_progname)
725 (*error_print_progname)();
726 else {
727 fprintf(stderr, "%s: ", get_program_name());
728 }
729
730 va_start (args, message);
731 error_tail(status, errnum, message, args);
732 }
733