How to close the file automatically when another application tries to open the same file?

How to close the file automatically when another application tries to open the same file?

Post by stev » Tue, 09 Jan 2007 00:43:46


I am writing a backup application which opens the file, read the data.
Another application needs that file sometimes to update the content.
Most time it works fine because the backup application opens the file
and closes it really quickly. But somtimes, I found while my backup
application had the file opened, another application failed. It looks
like another application opens the file without any sharing flag. As I
only can change the backup application written by myself, I think maybe
what I can do is to close the shared file when another appliation tries
to open the same file.

A small piece of testing code
===
HANDLE h1 = CreateFile("d:\\rubbish\\testcreatefile\\test.txt",
GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
0, OPEN_EXISTING, 0, 0);
printf("%X,%d\n", h1, GetLastError());
DisplayError();

HANDLE h2 = CreateFile("d:\\rubbish\\testcreatefile\\test.txt",
GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
printf("%X,%d\n", h2, GetLastError());
DisplayError();
===
7E8,0
The operation completed successfully.

FFFFFFFF,32
The process cannot access the file because it is being used by another
process.
===
The second CreateFile failed. What should I do for the first CreateFile
(in my backup application) to avoid such problem.

Thanks,
 
 
 

How to close the file automatically when another application tries to open the same file?

Post by Gary Chans » Tue, 09 Jan 2007 01:58:00


There isn't anything you can do about it, short of hooking CreateFile
and closing your file when the other program wants to open it.

- Gary Chanson (Windows SDK MVP)
- Abolish Public Schools

 
 
 

How to close the file automatically when another application tries to open the same file?

Post by stev » Tue, 09 Jan 2007 05:33:40

Anyone knows how Microsoft implements simliar functions in services
like Volume Shadow Copy Service, File Replication Service and Content
Indexing service. How these services won't affect running of any
application? Need a kernel mode file system filter driver?
 
 
 

How to close the file automatically when another application tries to open the same file?

Post by Gary Chans » Tue, 09 Jan 2007 14:57:47


I don't know, but that could be.

- Gary Chanson (Windows SDK MVP)
- Abolish Public Schools