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);
}
}
此法簡單有效,適用於需單例運行的後台服務或守護進程。