tags:

views:

94

answers:

2

How to lock file in Windows so that this file can be opened/read/wrote only by one process?

I found out that file can be locked with CreateFile by giving 0 to dwShareMode flag. It works but only the returned handle can be used to work with file. But I want to be able to lock the file to other processes and at the same time to create multiple handles in my process.

Please help me to solve this issue or give some tips...

+1  A: 

I don't think you can do that. The closest you can get is to use CreateFile to open/lock the file the first time and then use DuplicateHandle to create multiple handles from the one you already have

sbk
+2  A: 

Why do you need to create same file twice in the same process? You could use one handle in all I/O functions of your process without reopening file. If you need to pass the handle to another process you could use DuplicateHandle function.

Kirill V. Lyadvinsky
I am using various libraries in which they are calling CreateFile and it fails because the file is locked. So I was wondering is it possible to make the file locked for others, but not for my process.
matsoor
Your options are to pass handle to the libraries or do not lock the file.
Kirill V. Lyadvinsky