Search code examples
cfilefile-locking

How to ensure that when my process is operating on a file, no other process tries to write to it or delete it?


If my process is trying to read from a file, then how do I ensure from my code (C Language) that no other process either writes to it or deletes it (include system commands for deleting the file)?

Also, can this be achieved on all OS (Windows, Linux, Solaris, HP-UX, VxWorks etc)?


Solution

  • Edit: I'll answer for Unix/Linux

    As gspr and others said, take a look at file locking using fcntl, flock, etc. However, be warned that those are ADVISORY LOCKING methods.

    What does this mean? It means you can warn other processes that you are currently accesing a file, or a portion of it, but you can't forcibly keep them from ignoring you and writing all over your file.

    There are no COMPULSORY locking primitives. You can use permissions to your advantage, but you'll never have full guarantees -- the root user can always override your limitations. I don't think there's a way to work around that.