SoFunction
Updated on 2025-04-18

Detailed explanation of the example of implementing log backup daemon in C language

Training background

Suppose you are an operation and maintenance engineer and need to develop a simple log backup daemon for the company's monitoring system. This process needs to meet the following requirements:

  • Background operation: Leave the terminal and monitor log files in specified directories (such as /var/log/app/) for a long time.
  • Automatic backup: Compress and backup the newly added log files to the /backup/logs/ directory every 5 minutes.
  • Logging: Record the daemon's own operation log to /var/log/backup_daemon.log.
  • System service: manages the start, stop and status view of the process through systemd.

Environmental preparation

Operating system: Ubuntu 22.04 or CentOS 8 (requires root permissions)

tool:

  • Install the GCC compiler: sudo apt install gcc (Ubuntu) or sudo dnf install gcc (CentOS)
  • Text editor (such as vim or nano)

Directory creation:

sudo mkdir -p /var/log/app /backup/logs

Training steps

Task 1: Write daemon code (C language)

Goal: Create a daemon that is out of the terminal, monitor the directory and back up the files.

1. Write code backup_daemon.c

#include <>
#include <>
#include <>
#include <sys/>
#include <sys/>
#include <>
#include <>
#include <>
#include <>

void daemonize() {
    pid_t pid = fork();
    if (pid < 0) exit(EXIT_FAILURE);
    if (pid > 0) exit(EXIT_SUCCESS); // Parent process exits
    setsid();                        // Create a new session    chdir("/");                      // Switch the working directory    umask(0);                        // Reset file permission mask
    // Turn off standard input and output    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
}

void log_message(const char *message) {
    int fd = open("/var/log/backup_daemon.log", O_WRONLY | O_CREAT | O_APPEND, 0644);
    if (fd != -1) {
        time_t now = time(NULL);
        char buf[256];
        strftime(buf, sizeof(buf), "[%Y-%m-%d %H:%M:%S] ", localtime(&now));
        write(fd, buf, strlen(buf));
        write(fd, message, strlen(message));
        write(fd, "\n", 1);
        close(fd);
    }
}

void backup_logs() {
    DIR *dir = opendir("/var/log/app");
    if (!dir) {
        log_message("Failed to open log directory!");
        return;
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_REG) { // Ordinary files            char src_path[256], dest_path[256];
            snprintf(src_path, sizeof(src_path), "/var/log/app/%s", entry->d_name);
            snprintf(dest_path, sizeof(dest_path), "/backup/logs/%", entry->d_name);

            // Simulate compressed backup (actually call the tar command)            log_message("Backing up a log file...");
            char cmd[512];
            snprintf(cmd, sizeof(cmd), "tar -czf %s %s > /dev/null 2>&1", dest_path, src_path);
            system(cmd);
        }
    }
    closedir(dir);
}

int main() {
    daemonize();
    log_message("Daemon started successfully.");

    while (1) {
        backup_logs();
        sleep(300); // Execute every 5 minutes    }
    return 0;
}

2. Compile the code

gcc backup_daemon.c -o backup_daemon

Task 2: Configure as systemd service

Objective: Register the daemon as a system service to realize power-on and state management.

Create a service file

sudo vim /etc/systemd/system/backup_daemon.service

Write service configuration

[Unit]
Description=Log Backup Daemon
After=

[Service]
Type=simple
ExecStart=/usr/local/bin/backup_daemon
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=

Deploy and start the service

sudo cp backup_daemon /usr/local/bin/
sudo systemctl daemon-reload
sudo systemctl start backup_daemon
sudo systemctl enable backup_daemon

Verify service status

systemctl status backup_daemon

Task 3: Test and log viewing

Objective: Verify that the daemon's functions and logging are normal.

Generate test log files

sudo touch /var/log/app/

View the backup directory

ls /backup/logs  # It should appear in 5 minutes

View daemon log

tail -f /var/log/backup_daemon.log

Task 4: Debugging and Process Management

Goal: Use commands to manage daemons and debug problems.

View process information

ps -ef | grep backup_daemon

Stop service

sudo systemctl stop backup_daemon

Manually start debug mode

/usr/local/bin/backup_daemon  # Observe terminal output (requires service first)

Training summary

Through this case, students will master the following skills:

  • The core steps of writing daemons in C language (fork, setsid, closing file descriptor, etc.).
  • Register the process as a system service through systemd to achieve standardized management.
  • Logging and debugging methods to troubleshoot daemon operation problems.

Key points of knowledge

Daemon process features: background operation, departure from the terminal, long life cycle.

Steps to create a daemon: fork, setsid, close file descriptors, and redirect I/O.

systemd service management: service file writing, systemctl command use.

Log management: Record operation logs through files and view them using tail or journalctl.

Debugging skills: ps view process status, systemctl status analyzes service problems.

Extended thinking:

  • How to optimize backup logic (such as backing up only new files)?
  • How to implement daemon configuration hot loading through signals (such as SIGHUP)?

The above is a detailed explanation of the example of the C language implementation log backup daemon. For more information about C language log backup, please pay attention to my other related articles!