fatal function

I'm tired of writing this:

        if (some_test != 7) {
            fprintf (stderr, "%s:  some test failed, should have been 7, but got %d instead\n", progname, some_test);
            syslog (LOG_ERR, "some test failed, should have been 7, but got %d instead\n", some_test);
            exit (EXIT_FAILURE);
        }
    

So, I wrote a nice, simple little cover for it:

    /*
     *  fatal.c
     *
     *  (C) Copyright 2011 by Robert Krten, all rights reserved.
     *  This module is free software, but is incompatible with the GNU
     *  GPL because of its virus-like nature.  Other than that, do
     *  what you want with it.
     *
     *  This library module contains the following routine(s):
     *
     *      fatal_syslog_output
     *      fatal
     *
     *  fatal_syslog_output (facility)
     *      - enables syslog output with the "facility" name
     *      - output goes to stderr in all cases
     *
     *  fatal (predicate, fmt, ...)
     *      - if the predicate is false, does nothing
     *      - if true, prints the error message to stderr and, if fatal_syslog_output
     *        had been called, to syslogger as well.
     *
     *  ---------------------------------------------------------------------------
     *
     *  2011 07 03  R. Krten        created
    */

    #include 
    #include 
    #include 
    #include 

    extern  char    *progname;

    static  int     syslog_used = 0;

    void
    fatal_syslog_output (char *facility)
    {
        openlog (facility, LOG_PID | LOG_NDELAY, LOG_DAEMON);
        syslog_used = 1;
    }

    void
    fatal (int predicate, const char *fmt, ...)
    {
        char        buffer [1024];                          // 1024 + nul + optional \n
        va_list     arglist;

        if (!predicate) return;

        va_start (arglist, fmt);
        vsnprintf (buffer, sizeof (buffer), fmt, arglist);  // leave room for \n and NUL (hence the "- 2")
        va_end (arglist);

        if (syslog_used) {
            syslog (LOG_ERR, "Fatal error, %s", buffer);
        }
        fprintf (stderr, "%s:  fatal error, %s\n", progname, buffer);
        exit (EXIT_FAILURE);
    }
    

You can turn on syslog interaction by calling fatal_syslog_output() with the name of the facility. If you don't, it only logs to standard error.

Small, cheap, and converts the above example into one line:

        fatal (some_test != 7, "some test failed, should have been 7, but got %d instead", some_test);
    

Using your brain, you can modify this to disable syslog functionality with a new API, I never needed to.