daemons/t_syslog.cThis is daemons/t_syslog.c, an example to accompany the book, The Linux Programming Interface. This file is not printed in the book; it is the solution to Exercise 37-1 (page 782). The source code file is copyright 2024, Michael Kerrisk, and is licensed under the GNU General Public License, version 3. In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.
|
/* t_syslog.c Demonstrate the use of syslog(3) to write arbitrary messages to the system log. Usage is as shown in usageError() below. */ #include <syslog.h> #include "tlpi_hdr.h"
static void usageError(const char *progName) { fprintf(stderr, "Usage: %s [-p] [-e] [-l level] \"message\"\n", progName); fprintf(stderr, " -p log PID\n"); fprintf(stderr, " -e log to stderr also\n"); fprintf(stderr, " -l level (g=EMERG; a=ALERT; c=CRIT; e=ERR\n"); fprintf(stderr, " w=WARNING; n=NOTICE; i=INFO; d=DEBUG)\n"); exit(EXIT_FAILURE); }
int main(int argc, char *argv[]) { int options = 0; int level = LOG_INFO; int opt; while ((opt = getopt(argc, argv, "l:pe")) != -1) { switch (opt) { case 'l': switch (optarg[0]) { case 'a': level = LOG_ALERT; break; case 'c': level = LOG_CRIT; break; case 'e': level = LOG_ERR; break; case 'w': level = LOG_WARNING; break; case 'n': level = LOG_NOTICE; break; case 'i': level = LOG_INFO; break; case 'd': level = LOG_DEBUG; break; default: cmdLineErr("Bad facility: %c\n", optarg[0]); } break; case 'p': options |= LOG_PID; break; #if ! defined(__hpux) && ! defined(__sun) /* Not on HP-UX 11 or Solaris 8 */ case 'e': options |= LOG_PERROR; break; #endif default: fprintf(stderr, "Bad option\n"); usageError(argv[0]); } } if (argc != optind + 1) usageError(argv[0]); openlog(argv[0], options, LOG_USER); syslog(LOG_USER | level, "%s", argv[optind]); closelog(); exit(EXIT_SUCCESS); }
Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.