On a system I'm working on, there are several processes which occasionally write a certain file (we can think about it as a sort of a log, although it's not quite that). Unfortunately, they all write to the same output file, i.e. they overwrite it; and I can't control this behavior of theirs. Let's assume for the sake of discussion that the writes are disjoint and there are no races; and even that there's at least a bit of time between writes so that something can be done with the file.
Now, I want to maintain all the versions, for lack of a better word, of this file. In essence I want to "snatch" a copy whenever a write has occured, and save it elsewhere with a reasonable extra identifier (e.g. the time the write started, or the version index or what-not).
First, I was wondering if this is a common system administration task, or something esoteric. It's a bit reminiscent of log rotation, but isn't quite the same thing, since logs get appended to. Still, the snatching-and-maintaining earlier versions of a file is similar.
Second, and assuming I have to implement this myself - how do I "hook" myself onto the file being opened and closed? I don't want to poll it with fuser
even 1/nth of a second - that seems excessive. Or - perhaps there's another approach you would recommend to doing this?
The hook you are looking for is called inotify.
It's a Linux subsystem designed to monitor filesystem events, introduced about 15 years ago (it's not new). A good place to start would be the inotify-tools wiki.