该版本算是比较成熟的啦,欢迎大伙拿来试用!!!
1.新增数据库连接和备份时间配置文件conf
2.新增日志文件,程序运行的一些异常会记录在log文件下
后续的工作:
1.将代码切割为多个文件,分类存放代码
2.加入自动后台运行的支持
3.加入开机自动运行的支持
完成上面3个之后,我的linux c数据库备份程序就暂时靠一段落了。
使用提醒:
编译:gcc -o main main.c
后台启动:./main &
停止程序:./main stop
#include<sys/types.h> #include<sys/wait.h> #include<ctype.h> #include<unistd.h> #include<string.h> #include<stdlib.h> #include<signal.h> #include<time.h> #include<stdio.h> //程序运行的pid信息 #define PID_FILE "./pid.db" //记录待备份的数据库信息文件 #define DB_FILE "./db_list" //配置文件信息 #define CONF_FILE "./conf" //日志文件 #define LOG_FILE "./log" //最大备份的数据库数量 #define NUM 20 //数据库名字长度的限制 #define LEN 128 //程序轮询时间间隔 #define ALARM_TIME 10 //从文件读取到的数据库信息保存至该数组中 char *db_list[NUM]; //当前待备份的数据库数量 int read_num; //是否用户终止备份 int isbreak = 0; //数据库连接信息 typedef struct db_conf { char *host; char *user; char *pass; }CONF; //数据库备份时间 typedef struct bat_t { int hour; int min; }BAT_T; //malloc void malloc_dblist(); //free void free_dblist(); //读取待备份的数据库信息 int readDbFile(); //读取配置文件信息(数据库连接信息,备份时间等) CONF readConfFile(); //读取备份的时间信息 BAT_T readBatTFile(); //记录日志信息 void recordLog(char *); //信号处理函数 void signHandler(int sig); //记录程序运行的pid信息 int recordPid(int pid); //获取程序运行时的pid信息 int readPid(void); //移除程序运行时的pid信息 void delPid(void); int main(int argc, char *argv[]) { CONF conf; BAT_T bt; pid_t pid, old_pid; int i, prs; char buf[LEN]; time_t t; struct tm *tm_ptr; struct sigaction act, oldact; sigset_t newmask, suspmask, oldmask; if (argc >= 2) { old_pid = (pid_t)readPid(); //停止掉备份程序 if (strcmp(argv[1], "stop") == 0) { kill(old_pid, SIGINT); return 0; } else if (strcmp(argv[1], "restart") == 0) { kill(old_pid, SIGINT); sleep(5); } } old_pid = (pid_t)readPid(); //检测程序是否已经在运行 if (old_pid > 0) { fprintf(stderr, "Progress is running. "); return -1; } //记录程序运行的pid信息 prs = recordPid((int)getpid()); if (prs == -1) { fprintf(stderr, "Open pid.db file error. "); return -1; } //读取待备份的数据库 int rs = readDbFile(); if (rs) { delPid(); return rs; } //读取数据配置信息 conf = readConfFile(); //读取备份时间 bt = readBatTFile(); //信号接管 act.sa_handler = signHandler; sigemptyset(&act.sa_mask); act.sa_flags = 0; sigaction(SIGALRM, &act, 0); sigaction(SIGINT, &act, 0); while (1) { time(&t); tm_ptr = localtime(&t); //备份时间内进行备份 if (bt.hour == (int)tm_ptr->tm_hour && bt.min == (int)tm_ptr->tm_min) { for (i = 0; i < read_num; i++) { memset(buf, '