Einzelnen Beitrag anzeigen

Benutzerbild von Assarbad
Assarbad

Registriert seit: 8. Okt 2010
Ort: Frankfurt am Main
1.234 Beiträge
 
#3

AW: Lock File but My app still can read it?

  Alt 10. Feb 2011, 18:53
I won't store the content of file into memory, it will consume much memory. I wonder if there is any tricks or other API to solve my issue?
Absolutely. Use MMFs (memory mapped files) instead and open the file in a way that gives your process exclusive access.

See: MSDN-Library durchsuchenCreateFileMapping, MSDN-Library durchsuchenMapViewOfFileEx, MSDN-Library durchsuchenFlushViewOfFile, MSDN-Library durchsuchenUnmapViewOfFile

I reckon the set of API names does not necessarily give away how useful it is. You intend not to keep all of it in memory, fine. Go MMF. MMFs will allow you to map only a portion and even then this view is backed by the file itself. Consider it something like the principle of the page file, just inverse. But the best is that you can treat the mapped view as though it was a buffer in memory. The memory manager of Windows will take care that it gets paged back in whenever you access a page that has been paged out (i.e. is/was backed by the file you created the mapping of).

But may I ask why exactly - or rather what for - you need the locking? If you just want to prevent other processes from touching the file(s), why not open it exclusively with MSDN-Library durchsuchenCreateFile with only MSDN-Library durchsuchenFILE_SHARE_READ or even 0? Shouldn't that resolve your issue (even without MMF)? This will allow any other processes to open the file, but only for reading. So your process would be the only one able to write to the file using that particular handle (subsequent handles will have the same limitations, no matter whether inside your process or another one).
Oliver
"... aber vertrauen Sie uns, die Physik stimmt." (Prof. Harald Lesch)
  Mit Zitat antworten Zitat