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

StackOverflow https://stackoverflow.com/questions/3890515

  •  28-09-2019
  •  | 
  •  

문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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.

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.

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top