首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Linux C 實現 MySQL 定時備份工程實踐(含信號驅動與進程管理)

     編輯:關於C語言

Linux C 實現 MySQL 定時備份工程實踐(含信號驅動與進程管理)

專案目標與架構

  • 目標:讀取配置文件中的數據庫列表,定時調用 mysqldump 完成備份。
  • 版本:v1.0 基礎版(手動觸發),後續結合 cron/systemd timer 實現真正定時。
  • 平台:Linux/Unix(測試環境 Ubuntu Server 14.04 x64)。

核心模塊設計

1. 配置文件解析:健壯的行讀取

文件 db_list,每行一個數據庫名。避開 fgets 的換行符/不可見字符坑,改用 fgetc 逐字符構建:

void readDbFile() {
    FILE *fp = fopen(DB_FILE, "r");
    if (!fp) { fprintf(stderr, "%s not found\n", DB_FILE); exit(1); }
    malloc_dblist(); // 預分配指針數組
    int c, j = 0, read_num = 1, isnewline = 0;
    while ((c = fgetc(fp)) != EOF) {
        if (c == ' ' || c == '\0' || c == '\r' || !isprint(c)) continue;
        if (c == '\n') { j = 0; isnewline = 1; continue; }
        if (isnewline) { read_num++; isnewline = 0; }
        db_list[read_num-1][j++] = c;
    }
    fclose(fp);
    // 後續優化:改用 fscanf(fp, "%127s", buf) 自動跳過空白,更簡潔健壯
}

2. 進程模型:父進程監工,子進程幹活

pid_t pid = fork();
if (pid == 0) { // 子進程:串行備份每個庫
    for (i = 0; i < read_num; i++) {
        snprintf(buf, LEN, "mysqldump -uroot %s > %s.sql", db_list[i], db_list[i]);
        system(buf); // 簡單但阻塞;生產環境建議用 pipe + exec 避免 shell 注入
        printf("%d,%s\n", i, buf);
    }
    exit(0);
} else if (pid > 0) { // 父進程:等待回收
    int status;
    wait(&status);
    if (!WIFEXITED(status)) fprintf(stderr, "Child abnormal exit\n");
} else { perror("fork"); exit(1); }

3. 內存管理:分配/釋放配對

void malloc_dblist() {
    for (int i = 0; i < NUM; i++) {
        db_list[i] = malloc(LEN);
        memset(db_list[i], 0, LEN);
    }
}
void free_dblist() {
    for (int i = 0; i < NUM; i++) free(db_list[i]);
}

編譯與部署

# 1. 準備配置
echo -e "admin\nbook" > db_list

# 2. 編譯
gcc -o backup main.c

# 3. 手動測試
./backup

# 4. 定時部署(推薦 systemd timer)
# /etc/systemd/system/mysql-backup.service
[Unit]
Description=MySQL Daily Backup
[Service]
Type=oneshot
ExecStart=/opt/backup/backup
WorkingDirectory=/opt/backup

# /etc/systemd/system/mysql-backup.timer
[Unit]
Description=Run backup daily 02:00
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target

systemctl daemon-reload && systemctl enable --now mysql-backup.timer

已知不足與演進方向

關鍵知識點回顧

  1. fork 後子進程複製父進程文件描述符表,system 內部再 fork+exec,三進程模型需注意殭屍進程回收。
  2. 信號驅動定時(alarm/SIGALRM)在多線程/阻塞系統調用中不可靠,生產環境首選外部調度器。
  3. 配置解析是系統工程基石:fscanf/getline 比手寫狀態機更健壯。

這個小工程串聯了文件 I/O、進程控制、信號、字符串處理、系統運維,是 Linux C 系統編程的優秀入門實戰。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
問題解決方案
system() 命令注入風險改用 fork+execvp 直調 mysqldump,參數數組化
無錯誤碼檢查捕獲 mysqldump 返回碼,記錄日誌、告警
單線程串行備份慢線程池/進程池並行,控制併發數
無壓縮/加密/上傳管道接 gzip/openssl,上傳至 S3/OSS
硬編碼 root 無密碼配置文件讀取憑證,或使用 .my.cnf