通过文件独占的方式,我们打开指定的文件后,用 lockf 对文件加锁,结束程序时解锁文件。

下面代码中我们将当前程序的 PID 写入文件。

int writePidFile(const char *pidFile) {
    char str[32];
    int fd = open(pidFile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);

    if (fd < 0) {
        printf("Can't open pidFile %s.\n", pidFile);
        exit(1);
    }

    // Lock pidFile.
    if (lockf(fd, F_TLOCK, 0)) {
        printf("Can't lock pidFile %s.\n", pidFile);
        exit(0);
    }

    sprintf(str, "%d\n", getpid());
    // Write pid to pidFile.
    ssize_t len = strlen(str);

    if (write(fd, str, len) != len) {
        printf("Can't write pidFile %s.\n", pidFile);
        exit(0);
    }
    printf("Wrote pid file %s.\n", pidFile);
    return fd;
}

int main(){
    int pid_fd = writePidFile("server.pid");
    ...
    lockf(pid_fd, F_ULOCK, 0);
    close(pid_fd);
}

相关文章:

  • 2022-03-02
  • 2021-10-28
  • 2021-06-24
  • 2021-10-07
  • 2021-09-21
  • 2022-12-23
  • 2021-10-21
猜你喜欢
  • 2021-06-23
  • 2022-12-23
  • 2021-11-05
  • 2021-10-13
  • 2022-12-23
  • 2022-02-23
  • 2022-12-23
相关资源
相似解决方案