我想撰寫按需成為守護行程的程式:
if_there_are_no_daemon_alive_start_daemon();
pass_job_to_daemon();
我堅持實施if_there_are_no_daemon_alive_start_daemon. 起初我想嘗試鎖定檔案/run/lock/my-unique-name.lck,如果成功,則執行雙叉并完成,如果沒有,則守護程式已啟動并運行,是時候呼叫pass_job_to_daemon.
但是在父行程中獲得的檔案鎖,在父行程死亡后就消失了:
#include <assert.h>
#include <fcntl.h>
#include <sys/file.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
assert(argc > 1);
int fd = open(argv[1], O_WRONLY | O_APPEND | O_CREAT, 0600);
assert(fd >= 0);
int ret = flock(fd, LOCK_EX);
assert(ret == 0);
printf("get flock\n");
pid_t pid = fork();
assert(pid >= 0);
if (pid == 0) {
printf("child process\n");
sleep(5); //<-- no flock here according to lslocks
printf("child done\n");
} else {
printf("parent: time to exit\n");
}
return 0;
}
那么我可以在這里使用哪種處理器間鎖變體來檢查守護行程是否運行原子,然后在雙分叉后將此鎖傳遞給子行程而沒有問題?
uj5u.com熱心網友回復:
鎖定檔案不需要任何檔案鎖定,例如flock. 檔案的存在被用作鎖。添加O_EXCL到open通話中。如果open成功,你就有了鎖;然后釋放您remove或unlink檔案的鎖定。在崩潰的情況下,您需要對陳舊的鎖定檔案進行一些處理。這是它們通常在特定目錄中創建的原因之一,因為系統啟動腳本知道它并洗掉鎖定檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/517854.html
標籤:ClinuxUnix
上一篇:洗掉和壓縮目錄中的檔案
