training

Code I wrote during training
git clone git://git.bitsmanent.org/training
Log | Files | Refs | README

error.c (1825B)


      1 #include	<errno.h>		/* for definition of errno */
      2 #include	<stdarg.h>		/* ANSI C header file */
      3 #include	"ourhdr.h"
      4 
      5 static void	err_doit(int, const char *, va_list);
      6 
      7 char	*pname = NULL;		/* caller can set this from argv[0] */
      8 
      9 /* Nonfatal error related to a system call.
     10  * Print a message and return. */
     11 
     12 void
     13 err_ret(const char *fmt, ...)
     14 {
     15 	va_list		ap;
     16 
     17 	va_start(ap, fmt);
     18 	err_doit(1, fmt, ap);
     19 	va_end(ap);
     20 	return;
     21 }
     22 
     23 /* Fatal error related to a system call.
     24  * Print a message and terminate. */
     25 
     26 void
     27 err_sys(const char *fmt, ...)
     28 {
     29 	va_list		ap;
     30 
     31 	va_start(ap, fmt);
     32 	err_doit(1, fmt, ap);
     33 	va_end(ap);
     34 	exit(1);
     35 }
     36 
     37 /* Fatal error related to a system call.
     38  * Print a message, dump core, and terminate. */
     39 
     40 void
     41 err_dump(const char *fmt, ...)
     42 {
     43 	va_list		ap;
     44 
     45 	va_start(ap, fmt);
     46 	err_doit(1, fmt, ap);
     47 	va_end(ap);
     48 	abort();		/* dump core and terminate */
     49 	exit(1);		/* shouldn't get here */
     50 }
     51 
     52 /* Nonfatal error unrelated to a system call.
     53  * Print a message and return. */
     54 
     55 void
     56 err_msg(const char *fmt, ...)
     57 {
     58 	va_list		ap;
     59 
     60 	va_start(ap, fmt);
     61 	err_doit(0, fmt, ap);
     62 	va_end(ap);
     63 	return;
     64 }
     65 
     66 /* Fatal error unrelated to a system call.
     67  * Print a message and terminate. */
     68 
     69 void
     70 err_quit(const char *fmt, ...)
     71 {
     72 	va_list		ap;
     73 
     74 	va_start(ap, fmt);
     75 	err_doit(0, fmt, ap);
     76 	va_end(ap);
     77 	exit(1);
     78 }
     79 
     80 /* Print a message and return to caller.
     81  * Caller specifies "errnoflag". */
     82 
     83 static void
     84 err_doit(int errnoflag, const char *fmt, va_list ap)
     85 {
     86 	int		errno_save;
     87 	char	buf[MAXLINE];
     88 
     89 	errno_save = errno;		/* value caller might want printed */
     90 	vsprintf(buf, fmt, ap);
     91 	if (errnoflag)
     92 		sprintf(buf+strlen(buf), ": %s", strerror(errno_save));
     93 	strcat(buf, "\n");
     94 	fflush(stdout);		/* in case stdout and stderr are the same */
     95 	fputs(buf, stderr);
     96 	fflush(NULL);		/* flushes all stdio output streams */
     97 	return;
     98 }