防止一個進程被屢次啓動

open帶上o_create和o_execl,若是打開文件時,文件存在則返回錯誤。
這種作法比較簡單。

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int fd;

    while((fd = open("/tmp/hello.lock", o_creat | o_excl)) < 0){
        printf("file exist\n");
        sleep(1);
        continue;
    }
    close(fd);

    sleep(6);

    unlink("/tmp/hello.lock");
}ide

相關文章
相關標籤/搜索