in reply to Writing to a file atomically without renaming

No, not really. Not in UNIX systems at least. Of course, the word "atomic" is somewhat vague, you may want to define more precisely what you want.

Here are the alternatives. You can use file locking, but that's atomic only if the other program reading the file uses them too. You might hear of mandatory locking, but that doesn't really make a write atomic, as it could interrupt You can use link instead of rename, but I doubt that would help. You can always write a single byte atomically to a file, which is enough if you just want to change a flag. You can write to datagram sockets atomically (with the maximum size possibly restricted), but that doesn't substitutes real files. You can somehow make sure that all other services that could read the file are stopped, like going into single user mode and running only the process that writes the file; this will make the write practically atomic, but that's probably not what you want either.

You could create a mandatory lock or lease on the file, thus making it sure that no-one can open the file while you are doing the read; but someone can still have the file opened before you do that, and there is no way to tell if this is the case if it's some other user. If you are sure that only (non-setid) programs runnnig under your uid can have the file open, than this can be feasable.

So, the situation is like this: you can only do an atomic write if either

  1. If you can co-operate with other programs reading or writing the file at the same time. (This is the most frequent case.)
  2. It's enough for you that the write happens at one time, you don't care that someone reading the file might see a paritally changed file; and you are sure that no-one else wants to write the file, only read. In this case, you can use mandatory locking or leases, or even real-time processes (but that requires root privilage at least).
  3. If you can get set-id privilage for the owner of the file. You could create a set-id program for that user that does nothing but checks privilage and changes the file. (There are examples for such programs, although not for atomic access: like crontab.)
  4. If you can arrange that it is not a problem that the file has a different owner. You can make the directory writable only by a certain group, thus making it secure to do this.
  5. If you use a database instead of a file.
  6. If this is on some exotic operating system variant that has such a feature.
  7. I think I've forgot an option... I'm a bit disorganized now. If I remember it, I'll update the node.
  • Comment on Re: Writing to a file atomically without renaming