文件读/写锁定和取消链接 [英] File r/w locking and unlink

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

问题描述

我有以下问题.我想创建一个基于文件系统的会话存储,其中每个会话数据都存储在以会话ID命名的简单文件中.

I have following problem. I want to create a file system based session storage where each session data is stored in simple file named with session ids.

我想要以下API:write(sid,data,timeout)read(sid,data,timeout)remove(sid) 其中sid == file name,我还想拥有某种可以删除所有超时会话的GC.

I want following API: write(sid,data,timeout), read(sid,data,timeout), remove(sid) where sid==file name, Also I want to have some kind of GC that may remove all timed-out sessions.

如果您使用单个进程,则非常简单,但是使用多个进程甚至通过NFS绝对不容易.

Quite simple task if you work with single process but absolutly not trivial when working with multiple processes or even over NFS.

我想到的最简单的解决方案是:

The simplest solution I thought about was:

write/read:
   fd=open(file_name,O_CREAT | O_RDWR); // create a new file or use exsting
   fcntl_lock_file(fd)
   save data to fd/read data from fd
   fcntl_unlock_file(fd)
   close(fd)

GC:
   fd=open(file_name,O_RDWR);
   fcntl_lock_file(fd)
   if(timed_out)
      unlink(file_name)
   fcntl_unlock_file(fd)
   close(fd)

文件取消链接对文件名起作用而文件锁对文件起作用的最大问题 描述符.因此,以上情况在以下情况下将不起作用:

The biggest issue that file unlinking works on file names and file locks work on file descriptors. So the above would not work in following scenario:

GC - open,
write - open
GC - lock, unlink, unlock, close // file still exists because held by write
write - lock, write, unlock, close // file removed

有人知道如何解决此问题吗?有什么技巧可以允许 结合文件锁定和文件删除还是对文件进行原子操作?

Does anybody have an idea how such issue may be solved? Are there any tricks that allow combine file locking and file removal or make operation on file atomic?

注释:

  • 我不想使用数据库
  • 我正在寻找Unix的解决方案
  • 解决方案应与标准POSIX调用一起使用,例如fcnl,open,close,unlink

谢谢.

澄清,主要问题在于,对文件(名称-取消链接)的操作应通过文件描述符的操作-锁定来自动完成:

Clearification the major issue is that operation on files (names -- unlink) should be done atomically with operation of file descriptors -- locking:

  • 打开,取消链接-处理文件
  • fnctl-处理描述符

推荐答案

这行不通吗?

write/read:
   fd=open(file_name,O_CREAT | O_RDWR); // create a new file or use exsting
   fcntl_lock_file(fd)
   if stat(file_name).{st_dev, st_ino} != fstat(fd).{st_dev, st_ino}
       unlock, close, retry
   save data to fd/read data from fd
   fcntl_unlock_file(fd)
   close(fd)

如果stat失败并显示EEXIST(文件名不存在)或显示当前文件与您打开的文件不同,请保释.

If stat fails with EEXIST (file name does not exist) or shows that the current file is not the same as the one you opened, bail.

这篇关于文件读/写锁定和取消链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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