让程序最多只能有一个实例在运行(文件独占)

通过文件独占的方式,我们打开指定的文件后,用 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.
", pidFile);
        exit(1);
    }

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

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

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

int main(){
    int pid_fd = writePidFile("server.pid");
    ...
    lockf(pid_fd, F_ULOCK, 0);
    close(pid_fd);
}
原文地址:https://www.cnblogs.com/flipped/p/8837779.html