开发者

Is tellp safe to use with file locking

开发者 https://www.devze.com 2023-02-04 21:36 出处:网络
The general strategy for boost file locking (sharable and scoped file_locks), and file locking in general I think, is this:

The general strategy for boost file locking (sharable and scoped file_locks), and file locking in general I think, is this:

  1. open
  2. lock
  3. operate on file contents
  4. unlock
  5. close the file

However, I will be opening the file for append and want to call tellp to see where I am. Is this safe to do in the above scenario? Won't the file pointer be set as soon as the file is opened before the lock and thus potentially开发者_开发问答 not protected? If so, is there a standard idiom to get around this?


This may be environment-specific, but on the majority of platforms:

When a file is opened for append the file pointer is adjusted immediately before every write. So, if you use tellp before locking the file, it might not tell you where your newly appended bytes are going to go, but you shouldn't have two processes using locking somehow still appending the same range of bytes.


I recommend good boost documentation: http://www.boost.org/doc/libs/1_45_0/doc/html/interprocess/synchronization_mechanisms.html#interprocess.synchronization_mechanisms.file_lock

In which you can read:

  • file locks are not operating system locks, even if operating system supports it (e.g. Windows yes, Unix-like usually no), so if you lock file, anybody can read/write/delete it, unless other process uses same file locking mechanism. Thus think about it more like interprocess mutexes rather than real file locks.
  • file locks are for interprocess synchronization, they do not synchronize multiple threads within process
  • don't forget about flushing (ofstream's flush), so you do not have to worry about buffering

Oh, this is just awful... I wanted to help, I have written sample code, try it and ... as of 1_44 file locking is broken for win32, flushing does not work on locked file.

Sorry, not my fault.

If it helps, in theory: if you open file for appending, it means auto-seeking to end before every write operation. It does not stop you from manually seeking to end anytime you want - even without writing. However, experience (see above) says: stay away from broken things.

0

精彩评论

暂无评论...
验证码 换一张
取 消