文件锁定为Linux [英] File locks for linux

查看:155
本文介绍了文件锁定为Linux的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用临时文件:

char *temp = tempnam(NULL, "myapp_");
printf("Tempname: %s", temp)     // Prints /tmp/myapp_random
while (1) { }

但是,当我检查 / tmp目录(而应用程序仍在运行),该myapp_random是不存在的!

But when I check /tmp (while the app is still running), the myapp_random is not there!

对于使用文件锁定,我不能得到它把握好,我试图寻找在< fcntl.h> 但似乎把重点放在锁在一个文件中的特定部分。我只是想使用该文件完全是作为一个锁(这就是为什么我preFER试图临时文件的方法)。

As for using File Locks, I can't get a good grasp on it, I tried looking at <fcntl.h> but it seems to focus on locks in specified portions of a file. I just want to use the file entirely as a lock (which is why I prefer trying the temp file approach).

任何想法?

推荐答案

的tempnam 不的创建的文件,它只是给你一个文件名未在调用它的时候存在。

tempnam doesn't create the file, it just gives you a filename that didn't exist at the time you called it.

您仍然需要的创建的文件自己,因此仍然有竞争状态到另一个进程潜入你之前创建它。

You still have to create the file yourself and therefore still have the race condition that another process may sneak in and create it before you.

您不实际的希望的使用的tempnam ,因为这将使每个进程自身的文件名,他们将能够同时运行。你需要的是一个的固定的每个进程打开,然后文件名(如 /tmp/myapp.lck )后尝试羊群

You don't actually want to use tempnam since that will give each process its own file name and they will be able to run concurrently. What you need is a fixed file name (like /tmp/myapp.lck for example) which each process opens and then attempts to flock.

您是用羊群更好的锁定文件,的fcntl 会给你锁定一个更精细(部分文件),但是这不是真的在这里的要求。

You're better off with flock for a lock file, fcntl will give you a finer grain of locking (parts of files) but that's not really a requirement here.

在code将运行是这样的:

The code would run something like this:

if ((mylockfd = open ("/tmp/myapp.lck", O_CREAT | O_RDWR, 0666)) < 0) {
    // error, couldn't open it.
    return;
}
if (flock (mylockfd, LOCK_EX | LOCK_NB) < 0) {
    // error, couldn't exclusive-lock it.
    return;
}
:
// Weave your magic here.
:
flock (mylockfd, LOCK_UN);

这可能需要一些工作,但应该是一个良好的开端。一个更广义的解决办法是这样的:

That probably needs some work but should be a good start. A more generalised solution would be something like:

int acquireLock (char *fileSpec) {
    int lockFd;

    if ((lockFd = open (fileSpec, O_CREAT | O_RDWR, 0666))  < 0)
        return -1;

    if (flock (mylockfd, LOCK_EX | LOCK_NB) < 0) {
        close (lockFd);
        return -1;
    }

    return lockFd;
}

void releaseLock (int lockFd) {
    flock (lockFd, LOCK_UN);
    close (lockFd);
}

// Calling code here.

int fd;
if ((fd = acquireLock ("/tmp/myapp.lck")) < 0) {
    fprintf (stderr, "Cannot get lock file.\n");
    return 1;
}

// Weave your magic here.

releaseLock (fd);

这篇关于文件锁定为Linux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆