羊群():没有竞争条件删除锁定的文件? [英] flock(): removing locked file without race condition?

查看:142
本文介绍了羊群():没有竞争条件删除锁定的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用羊群()名为互斥进程间(即某些进程可以决定举行的some_name,它是通过锁定在一个临时目录中名为some_name文件实施了锁:

I'm using flock() for inter-process named mutexes (i.e. some process can decide to hold a lock on "some_name", which is implemented by locking a file named "some_name" in a temp directory:

lockfile = "/tmp/some_name.lock";
fd = open(lockfile, O_CREAT);
flock(fd, LOCK_EX);

do_something();

unlink(lockfile);
flock(fd, LOCK_UN);

锁定文件应该在某个时候被删除,以避免与数百个文件填充临时目录。

The lock file should be removed at some point, to avoid filling the temp directory with hundreds of files.

然而,在这个code明显的竞争条件;例如与进程A,B和C:

However, there is an obvious race condition in this code; example with processes A, B and C:

A opens file
A locks file
B opens file
A unlinks file
A unlocks file
B locks file (B holds a lock on the deleted file)
C opens file (a new file one is created)
C locks file (two processes hold the same named mutex !)

有没有一种方法,以消除在某个时刻锁定文件,而不会引入这种竞争情况?

Is there a way to remove the lock file at some point without introducing this race condition ?

推荐答案

很抱歉,如果我回答一个死的问题:

Sorry if I reply to a dead question:

锁定文件后,打开它的另一个副本,FSTAT两个副本,并检查inode编号,如:

After locking the file, open another copy of it, fstat both copies and check the inode number, like this:

lockfile = "/tmp/some_name.lock";

    while(1) {
        fd = open(lockfile, O_CREAT);
        flock(fd, LOCK_EX);

        fstat(fd, &st0);
        stat(lockfile, &st1);
        if(st0.st_ino == st1.st_ino) break;

        close(fd);
    }

    do_something();

    unlink(lockfile);
    flock(fd, LOCK_UN);

这prevents的竞争条件,因为如果一个程序持有的文件仍然是文件系统上的锁,具有剩余文件所有其他项目将有一个错误的inode编号。

This prevents the race condition, because if a program holds a lock on a file that is still on the file system, every other program that has a leftover file will have a wrong inode number.

其实,我证明了它的状态机模型,使用以下属性:

I actually proved it in the state-machine model, using the following properties:

如果P_i有锁定在文件系统中的描述符,然后没有其他进程处于关键的部分。

If P_i has a descriptor locked on the filesystem then no other process is in the critical section.

如果P_i是用正确的i节点或在临界区统计后,它锁定在文件系统描述符。

If P_i is after the stat with the right inode or in the critical section it has the descriptor locked on the filesystem.

这篇关于羊群():没有竞争条件删除锁定的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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