zoukankan      html  css  js  c++  java
  • 让程序最多只能有一个实例在运行(文件独占)

    通过文件独占的方式,我们打开指定的文件后,用 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);
    }
    
  • 相关阅读:
    一个自动化测试工具 UI Recorder
    通俗理解http2.0
    IE 问题集合
    webpack
    性能工具集合
    网络 问题
    css命名规范
    ajax 总结
    CSS深入理解学习笔记之relative
    jQuery插件开发通用框架
  • 原文地址:https://www.cnblogs.com/flipped/p/8837779.html
Copyright © 2011-2022 走看看