linux c数据库备份第二版

#想知道更多请查看第一版"linux c数据库备份第一版"

  1 #include<sys/types.h>
  2 #include<sys/wait.h>
  3 #include<ctype.h>
  4 #include<unistd.h>
  5 #include<string.h>
  6 #include<stdlib.h>
  7 #include<stdio.h>
  8 
  9 //待备份的数据表文件(一个数据库一行)
 10 #define DB_FILE "./db_list"
 11 //最多可以备份的数据库数量
 12 #define NUM 20
 13 //一个数据库名字的最长字符数
 14 #define LEN 128
 15 //保存从DB_FILE中读取到的数据库
 16 char *db_list[NUM];
 17 //从DB_FILE文件中读取到的数据库数量
 18 int read_num;
 19 //请求内存函数
 20 void malloc_dblist();
 21 //释放内存函数
 22 void free_dblist();
 23 //读取数据库文件
 24 void readDbFile();
 25 
 26 int main(int argc, char *argv[]) {
 27     pid_t pid;
 28     int i;
 29     char buf[LEN];
 30 
 31     //从文件读取数据库信息
 32     readDbFile();
 33     
 34     pid = fork();
 35 
 36     if (pid < 0) {
 37         fprintf(stderr, "fork error\n");
 38         exit(1);
 39     }
 40     
 41     switch (pid) {
 42         case -1:
 43             fprintf(stderr, "fork failed\n");
 44             exit(1);
 45         case 0:
 46             //子进程进行数据库的备份
 47             for (i = 0; i < read_num; i++) {
 48                 memset(buf, '\0', LEN);
 49                 sprintf(buf, "%s%s%s%s%s", "mysqldump -uroot ", db_list[i], " > ", db_list[i], ".sql");
 50                 system(buf);
 51                 printf("%d,%s\n", i, buf);
 52             }
 53             break;
 54     }
 55     //等待子进程的结束
 56     if (pid > 0) {
 57         int stat_val;
 58         pid_t child_pid;
 59         
 60         child_pid = wait(&stat_val);
 61         
 62         if (!WIFEXITED(stat_val)) {
 63             fprintf(stdout, "Child terminated abnormaly\n");
 64         }
 65         exit(1);
 66         
 67     }
 68     
 69     free_dblist();
 70     
 71     exit(0);
 72     
 73 }
 74 
 75 void malloc_dblist()
 76 {
 77     int i = 0;
 78     //malloc for db_list
 79     for (i = 0; i < NUM; i++) {
 80         db_list[i] = malloc(LEN);
 81         memset(db_list[i], '\0', LEN);
 82     }
 83 }
 84 void free_dblist()
 85 {
 86     int i;
 87     //free db_list's memory
 88     for (i = 0; i < NUM; i++) {
 89         free(db_list[i]);
 90     }
 91 }
 92 
 93 void readDbFile()
 94 {
 95     FILE *fp;
 96     
 97     fp = fopen(DB_FILE, "r");
 98     if (!fp) {
 99         fprintf(stderr, "%s not found\n", DB_FILE);
100     }
101     else {
102         malloc_dblist();
103         
104         read_num = 0;
105         while (fscanf(fp, "%127[^\r\n]\n", db_list[read_num]) == 1) {
106             puts(db_list[read_num]);
107             read_num++;
108         }
109         
110         fclose(fp);    
111     }
112     
113 }

 

posted @ 2015-07-18 16:49  齐泽西  阅读(151)  评论(0编辑  收藏  举报