Skip to content

Commit

Permalink
Introduce colored fatal error messages
Browse files Browse the repository at this point in the history
Introduces the fatal() function that
1) Check whether stderr is a terminal, and sets red text color if it is
2) Prints the message
3) Exits the app
  • Loading branch information
rfjakob committed Jul 18, 2018
1 parent 1e5f823 commit 0aaaf7c
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

# generated from MANPAGE.md
/earlyoom.1
/earlyoom.1.gz

# generated service files
/earlyoom.service
Expand Down
25 changes: 25 additions & 0 deletions msg.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// SPDX-License-Identifier: MIT

#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <unistd.h>

// Print message to stderr and exit with "code".
// Example: fatal(6, "could not compile regexp '%s'\n", regex_str);
void fatal(int code, char* fmt, ...)
{
char* red = "";
char* reset = "";
if (isatty(fileno(stderr))) {
red = "\033[31m";
reset = "\033[0m";
}
char fmt2[100];
snprintf(fmt2, sizeof(fmt2), "%sfatal: %s%s", red, fmt, reset);
va_list args;
va_start(args, fmt); // yes fmt, NOT fmt2!
vfprintf(stderr, fmt2, args);
va_end(args);
exit(code);
}
7 changes: 7 additions & 0 deletions msg.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/* SPDX-License-Identifier: MIT */
#ifndef MSG_H
#define MSG_H

void fatal(int code, char* fmt, ...);

#endif

0 comments on commit 0aaaf7c

Please sign in to comment.