lock2.c

来自「source code of begin linux programming」· C语言 代码 · 共 31 行

C
31
字号
#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <fcntl.h>#include <errno.h>const char *lock_file = "/tmp/LCK.test2";int main() {    int file_desc;    int tries = 10;    while (tries--) {        file_desc = open(lock_file, O_RDWR | O_CREAT | O_EXCL, 0444);        if (file_desc == -1) {            printf("%d - Lock already present\n", getpid());            sleep(3);        }        else {                /* critical region */            printf("%d - I have exclusive access\n", getpid());            sleep(1);            (void)close(file_desc);            (void)unlink(lock_file);                /* non-critical region */            sleep(2);        }    } /* while */    exit(EXIT_SUCCESS);}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?