出错处理模块和运行日志模块设计
出错处理模块
该模块由bterror.h和bterror.c文件构成,主要定义了一些错误类型,以及发生导致程序终止的致命性错误时程序的响应。
以下是bterror,h的内容:
//bterror.h
#ifndef BTERROR_H
#define BTERROR_H
#define FILE_FD_ERR -1 // 无效的文件描述符
#define FILE_READ_ERR -2 // 读文件失败
#define FILE_WRITE_ERR -3 // 写文件失败
#define INVALID_METAFILE_ERR -4 // 无效的种子文件
#define INVALID_SOCKET_ERR -5 // 无效的套接字
#define INVALID_TRACKER_URL_ERR -6 // 无效的Tracker URL
#define INVALID_TRACKER_REPLY_ERR -7 // 无效的Tracker回应
#define INVALID_HASH_ERR -8 // 无效的hash值
#define INVALID_MESSAGE_ERR -9 // 无效的消息
#define INVALID_PARAMETER_ERR -10 // 无效的函数参数
#define FAILED_ALLOCATE_MEM_ERR -11 // 申请动态内存失败
#define NO_BUFFER_ERR -12 // 没有足够的缓冲区
#define READ_SOCKET_ERR -13 // 读套接字失败
#define WRITE_SOCKET_ERR -14 // 写套接字失败
#define RECEIVE_EXIT_SIGNAL_ERR -15 // 接收到退出程序的信号
// 用于提示致命性的错误,程序将终止
void btexit(int errno,char *file,int line);
#endif
以下是bterror.c文件:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "bterror.h"
void btexit(int errno,char *file,int line)
{
printf("exit at %s : %d with error number : %d\n",file, line, errno);
exit(errno);
}
运行日志模块
该模块由log.h和log.c组成,负责记录运行的日志,而日志是用来查询和分析程序行为。
以下是log.h文件:
//log.h
#ifndef LOG_H
#define LOG_H
#include <stdarg.h>
//用于记录程序的文件
void logcmd(char *fmt,...);
//打开日志文件
int init_logfile(char *filename);
//将程序运行日志记录到文件
int logfile(char *file, int line, char *msg);
#endif
以下是log.c文件://log.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include "log.h"
//日志文件的描述符
int logfile_fd = -1;
/*
*功能:在命令行上打印一条日志
*传入参数:fmt ...
*传出参数:
*返回值:
*/
void logcmd(char *fmt,...)
{
va_list ap;
va_start(ap, fmt);
vprintf(fmt, ap); //标准化输出
va_end(ap);
}
/*
*功能:打开记录日志的文件
*传入参数:filename
*传出参数:
*返回值:
* 0 打开成功
* -1 未打开
*/
int init_logfile(char *filename)
{
logfile_fd = open(filename,O_RDWR|O_CREAT|O_APPEND,0666);
if(logfile_fd < 0)
{
printf("open logfile failed\n");
return -1;
}
return 0;
}
/*
*功能:将一条日志写入日志文件
*传入参数:file line msg
*传出参数:
*返回值:
* 0 成功
*/
int logfile(char *file,int line,char *msg)
{
char buff[256];
if(logfile_fd < 0) return -1;
snprintf(buff,256,"%s:%d %s\n",file,line,msg);
write(logfile_fd,buff,strlen(buff));
return 0;
}
程序说明:函数logcmd是一个变长参数的函数(参考printf函数),也就是函数的参数个数是可变的。语句“logcmd("%s:%d error\n", __FILE__,__LINE__);”的功能与“printf("%s:%d error\n", __FILE__, __LINE__);”功能相同。