concurrently writing and renaming file

Viewed 33

I have to maintain a data file data.cur which has to be rolled to a new file data. periodically. So I am renaming the file periodically, and write to new file when timeout. Renaming and writing to a file are done in different threads. When these are done concurrently, how to synchronize them?

1 Answers

The problem may be OS dependent. On Windows it is not possible to rename/move/delete a file while it is open by some process. On Linux, you can rename/move/delete a directory entry while a process has a file handle, but the process keeps writing to the original file and not necesarily to the new file you intend to have. So a smart solution may be necessary.

The use case itself looks very much like log4j's RollingFileAppender. So you may want to check how they solved it. Apart from that, tools like logrotate can ease some pain on *nix systems.

Related