2.13 Exercise: Message Logging

Team-FLY

The exercise in this section describes a logging library that is similar to the list object defined in listlib.h and listlib.c of Program 2.6 and Program 2.7, respectively. The logging utility allows the caller to save a message at the end of a list. The logger also records the time that the message was logged. Program 2.11 shows the log.h file for the logger.

Program 2.11 log.h

The header file log.h for the logging facility .

 #include <time.h> typedef struct data_struct {      time_t time;      char *string; } data_t; int addmsg(data_t data); void clearlog(void); char *getlog(void); int savelog(char *filename); 

The data_t structure and the addmsg function have the same respective roles as the list_t structure and adddata function of listlib.h . The savelog function saves the logged messages to a disk file. The clearlog function releases all the storage that has been allocated for the logged messages and empties the list of logged messages. The getlog function allocates enough space for a string containing the entire log, copies the log into this string, and returns a pointer to the string. It is the responsibility of the calling program to free this memory when necessary.

If successful, addmsg and savelog return 0. A successful getlog call returns a pointer to the log string. If unsuccessful , addmsg and savelog return “1. An unsuccessful getlog call returns NULL . These three functions also set errno on failure.

Program 2.12 contains templates for the four functions specified in log.h , as well as the static structures for the list itself. Complete the implementation of loglib.c . Use the logging facility to save the messages that were printed by some of your programs. How might you use this facility for program debugging and testing?

Program 2.12 loglib.c

A template for a simple logging facility .

 #include <stdlib.h> #include <string.h> #include "log.h" typedef struct list_struct {      data_t item;      struct list_struct *next; } log_t; static log_t *headptr = NULL; static log_t *tailptr = NULL; int addmsg(data_t data) {    return 0; } void clearlog(void) { } char *getlog(void) {    return NULL; } int savelog(char *filename) {    return 0; } 
Team-FLY


Unix Systems Programming
UNIX Systems Programming: Communication, Concurrency and Threads
ISBN: 0130424110
EAN: 2147483647
Year: 2003
Pages: 274

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net