Lock the file so that it is not deleted

I work with two independent c / C ++ applications on Windows, where one of them constantly updates the image on disk (from a web camera), and the other reads this image for processing. This works fine and dandy 99.99% of the time, but from time to time the reader application is in the middle of reading the image when the author removes it in order to update it with a new one.

The obvious solution for me, it seems, is that the reader has some kind of lock in the file so that the writer can see that he cannot delete it and thus block it until he can delete and update. is there any way to do this? Or is there another simple design pattern that I can use to get the same constant image refresh between two programs?

Thank,

-Robert

+3
source share
7 answers

Try using a synchronization object, the mutex may work. Whenever a process wants to read or write to a file, it must first obtain a mutex lock.

+4
source

Yes, a locking mechanism will help. There are, unfortunately, several to choose from. Linux / Unix for example. has flock (2), Windows has a similar (but different) mechanism.

Another (somewhat hacky) solution is to simply write the file under a temporary name and then rename it. Many file systems ensure that renaming is atomic, so this may work. However, it depends on fs, so it is a bit hacked.

+3
source

Windows API, CreateFile 0, dwShareMode .

:

, , .

ReadFile, WriteFile, CloseFile .., C.

+3

, kludge, (, .lock) . , .lock.

, Open Office ( ), , , , , .

+2

, ; , :

:

1.

2 , .

3, , , , 1 2 (); , , 1

4 , ( , , , PID, , , , , , , .., :

  • A , .
  • , ,
  • B , , , .
  • A , , , , , ,
  • B , (-) ( A) -
+1

, , ? , , . , ( ), . , , , . , . .

0

? ('n' : -)

Not too much to fill your disk, but for sure 3 will be enough? if not, you write faster than you can handle, and you have a fundamental anyhoo problem (configure it to detect "n").

Loop overwrite.

0
source

Source: https://habr.com/ru/post/1740089/


All Articles