萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 防止程式重複執行:檔案鎖機制實作範例

使用檔案鎖防止程式重複運行

Linux 系統可透過檔案鎖機制確保程式僅運行單一實例。啟動時檢查鎖定檔是否存在,存在則表示已在運行直接退出;不存在則建立檔案寫入當前 PID,程式結束時刪除鎖定檔。

實現原理

利用 open() 系統呼叫的 O_CREAT | O_EXCL 旗標,確保鎖定檔建立的原子性。兩進程同時嘗試建立同一檔案時,僅第一個成功,第二個收到 EEXIST 錯誤,避免重複啟動。

程式碼範例

static char file_lock[sizeof(ctl_addr.sun_path)] = "/var/run/file.pid";
static bool file_lock_created = FALSE;

static int create_lock(void) {
    int fd = open(file_lock, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC,
                  S_IRUSR | S_IRGRP | S_IROTH);
    if (fd < 0) {
        if (errno == EEXIST) {
            fprintf(stderr, "file: lock file \"%s\" already exists\n", file_lock);
            exit_file(10);
        } else {
            fprintf(stderr, "file: unable to create lock file \"%s\" (%d %s)\n",
                    file_lock, errno, strerror(errno));
            exit_file(1);
        }
    }
    file_lock_created = TRUE;
    return fd;
}

static bool fill_lock(int lockfd) {
    char buf[30];
    pid_t pid;
    int len;
    pid = getpid();
    len = snprintf(buf, sizeof(buf), "%u\n", (unsigned int) pid);
    bool ok = len > 0 && write(lockfd, buf, len) == len;
    close(lockfd);
    return ok;
}

static void delete_lock(void) {
    if (file_lock_created) {
        unlink(file_lock);
    }
}

函式說明

  • create_lock():嘗試建立鎖定檔,檔案已存在則退出程式
  • fill_lock():將當前進程 PID 寫入鎖定檔,方便後續排查
  • delete_lock():程式退出時刪除鎖定檔,釋放資源

此法簡單有效,適用於需單例運行的後台服務或守護進程。

copyright © 萬盛學電腦網 all rights reserved