使用boost :: interprocess :: file_lock创建一个锁定的文件

Edw*_*per 6 c++ boost file-locking interprocess boost-interprocess

我想用它boost::interprocess::file_lock来确保x进程写入目录的文件在完成之前P1不会被进程读取P2.要做到这一点,我想在编写P1文件boost::interprocess::file_lock时锁定文件,然后在文件完成时将其解锁.然后P2可以跳过(并返回)任何被锁定的文件.

我遇到的问题是它似乎boost::interprocess::file_lock只允许你锁定存在的文件.但是,如果我首先创建文件,然后锁定它,那么就存在竞争条件:

  1. P1 创建文件
  2. P2 注意到文件并开始阅读
  3. P1 锁定文件
  4. P1 写一些数据
  5. P2读取一些数据,到达终点,最后只得到部分P1输出.

所以我想做的就是创建一个文件,并在创建文件后立即将其锁定.有没有办法使用boost::interprocess::file_lock

小智 5

您误解了 boost::interprocess::file_lock 的目的,当您使用 boost::interprocess::file_lock test_lock("my_file") 方法创建 file_lock 时,您并没有保护文件“my_file”不
被其他进程读取/写入,你只要声明你有一个引用文件“my_file”的锁,如果其他进程也有引用同一个文件的锁,你可以实现这些锁之间的互斥,但这些锁不关心读/write 对文件“my_file”的操作,该文件只是一个标志


Jos*_*man 2

不会。但是有一种解决方法,只使用一个额外的空文件。

在 P2 尝试扫描文件之前,请创建一个 P1 和 P2 都知道的名称的空文件。在 P2 开始扫描之前,它将锁定该空文件,并在完成扫描目录后释放锁定(即,在从文件读取数据时不应持有锁定)。在 P1 创建新文件之前,它将锁定该空文件,并在新文件创建锁定后释放锁定。