码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-04-15 11:48:46      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:程序   usr   指定   代码   print   can   span   const   实例   

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

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

标签:程序   usr   指定   代码   print   can   span   const   实例   

原文地址:https://www.cnblogs.com/flipped/p/8837779.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!