views:

84

answers:

4

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)?

A: 

You have to open the file with READ sharing permissions, which means anyone else trying to open it can only get read access. As @Pointy says, this is OS specific and you'll probably have to code this separately for Windows, Linux, etc. However, most modern OSs should support this.

Assaf Lavie
+1  A: 

For POSIX systems, take a look at fcntl. flock could also be of interest, although I don't think it's a part of POSIX.

gspr
+3  A: 

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.

Santiago Lezica
A: 

Copy the file, make your changes, then rename it back over the original.

Another method, if the file doesn't yet exist, is to create the file using exclusive flags, then delete it from the filesystem. Perform your writing, then hard link it back into the filesystem (it presently exists only as an open inode). You can make use of /proc for the source path.

Matt Joiner