0

What would happen if I reopen an fstream with data in it using the std::ios::trunc flag without closing a process and whilst my process holds a boost::interprocess::file_lock()?

Should I expect the OS to maintain my file lock? Or will the OS transparently unregister the lock when the file is closed? Both Windows and POSIX experience would be appreciated.

edit

my main goal is to truncate a config file and rewrite it. The secondary purpose of the file is to prevent other equivalent daemons from starting up. So if there is another way using boost or c++ stl to truncate a file without closing it, I'm all ears :D

Hassan Syed
  • 20,075
  • 11
  • 87
  • 171
  • Assuming your OS supports file locking at all, your reopen should just fail, unless I misunderstand something somewhere... – Billy ONeal Mar 06 '12 at 17:59
  • lets assume I am using a modern posix/winapi implementation (say something from the last decade or two ?) – Hassan Syed Mar 06 '12 at 18:02
  • IIRC POSIX does not do file locking. I think Linux supports it as a nonstandard extension, and I don't think most BSDs support it at all. I could be wrong though. – Billy ONeal Mar 06 '12 at 18:09
  • does it matter if it is standard or non-standard ? I am sorry I erroneously used the posix tag. lets assume any unix os that is in active development and that calls itself partially posix compliant. – Hassan Syed Mar 06 '12 at 18:12
  • BSD is under active development and calls itself posix compliant. – Billy ONeal Mar 06 '12 at 18:13
  • sure, fine, BSD then, I don't care if it's advisory or enforced. – Hassan Syed Mar 06 '12 at 18:20

1 Answers1

0

Empirically : reopening a file using std::fstream::close followed by std::fstream::open will drop the lock transparently, (as tested with linux command lsof) after doing this the lock needs to be re-acquired using boost::interprocess.

So, as long as you follow the open-file followed by acquire-lock, you should be fine.

You might want to run the same test in windows.

Hassan Syed
  • 20,075
  • 11
  • 87
  • 171