linux cDatabase Backup第一版

來源:互聯網
上載者:User

標籤:

使用linuxC實現的mysqlDatabase Backup
目標:通過alarm訊號定時備份資料庫
備忘:目前是第一個版,本身不能定時備份可以結合linux自動化實現定時備份。
運行平台:Linux或類unix
測試平台:ubuntu server 14.04 x64
檔案資訊:
main.c:Database Backup程式
db_list:待備份的資料庫資訊,一行一個檔案。
不足:
檔案的讀取方式感覺還不到位,使用的是fgetc一個個字元讀取然後過濾和組合來讀取相關的資料庫資訊;開始使用的是fgets函數處理的時候,遇到了很多的麻煩,比如讀取到斷行符號字元\r,讀取到換行字元\n,讀取到不可見字元等,後面信心大受傷所以改用了fgetc實現了。目前測試還是挺良好的,也歡迎大家提出更好的解決方案。(註:昨晚已經使用fscanf函數解決了這個問題,晚點會更新上來)

編譯和運行:
首先把要備份的資料庫名寫進db_list檔案裡面一行一個資料庫,如
admin
book
然後編譯和運行
$gcc -o mian main.c
$./main

下面是main.c檔案內容:

#include<sys/types.h>#include<sys/wait.h>#include<ctype.h>#include<unistd.h>#include<string.h>#include<stdlib.h>#include<stdio.h>//待備份的資料表檔案(一個資料庫一行)#define DB_FILE "./db_list"//最多可以備份的資料庫數量#define NUM 20//一個資料庫名字的最長字元數#define LEN 128//儲存從DB_FILE中讀取到的資料庫char *db_list[NUM];//從DB_FILE檔案中讀取到的資料庫數量int read_num;//請求記憶體函數void malloc_dblist();//釋放記憶體函數void free_dblist();//讀取資料庫檔案void readDbFile();int main(int argc, char *argv[]) {pid_t pid;int i;char buf[LEN];//從檔案讀取資料庫資訊readDbFile();pid = fork();if (pid < 0) {fprintf(stderr, "fork error\n");exit(1);}switch (pid) {case -1:fprintf(stderr, "fork failed\n");exit(1);case 0://子進程進行資料庫的備份for (i = 0; i < read_num; i++) {memset(buf, ‘\0‘, LEN);sprintf(buf, "%s%s%s%s%s", "mysqldump -uroot ", db_list[i], " > ", db_list[i], ".sql");system(buf);printf("%d,%s\n", i, buf);}break;}//等待子進程的結束if (pid > 0) {int stat_val;pid_t child_pid;child_pid = wait(&stat_val);if (!WIFEXITED(stat_val)) {fprintf(stdout, "Child terminated abnormaly\n");}exit(1);}free_dblist();exit(0);}void malloc_dblist(){int i = 0;//malloc for db_listfor (i = 0; i < NUM; i++) {db_list[i] = malloc(LEN);memset(db_list[i], ‘\0‘, LEN);}}void free_dblist(){int i;//free db_list‘s memoryfor (i = 0; i < NUM; i++) {free(db_list[i]);}}void readDbFile(){FILE *fp;int i, j, c, isnewline;char *rs;char tmpbuf[LEN];fp = fopen(DB_FILE, "r");if (!fp) {fprintf(stderr, "%s not found\n", DB_FILE);}else {malloc_dblist();read_num = 1;j = 0;isnewline = 0;while (!feof(fp)) {c = fgetc(fp);//Null 字元或者字串結束字元if (c == ‘ ‘ || c == ‘\0‘) {continue;}//斷行符號字元if (c == ‘\r‘) {continue;}//換行字元if (c == ‘\n‘) {j = 0;isnewline = 1;continue;}//不可列印字元if (!isprint(c)) {continue;}if (isnewline) {read_num++;isnewline = 0;}db_list[read_num-1][j] = c;j++;}fclose(fp);}}

  

下面是資料庫資訊檔db_list:

adminbook

 

linux cDatabase Backup第一版

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.