简体   繁体   中英

MFC C++: how can I lock a file to be used only in my process?

I'd like to lock a couple of files to be only used by my process, denying any other application access to these files while my program is running. Of course I know that I can get exclusive access to a file using Createfile, but my application works differently, I read a bunch of filenames froma config, and process these files with a Lib linked to my application, ie one of the functions in my lib accesses the files, but I don't get a filoehandle or something similar in return.

So what I want to acchieve is that while my app is processing these files, no other application can modify them. Is this somehow possible? I am developing using MFC in Visual Studio 8.

我从未使用过它们,但是LockFile/LockFileEx文档说: 锁定指定的文件以供调用进程进行独占访问。

You need cooperation from the OS, because that's the only way to influence other processes.

The OS requires that you use handles to refer to files. It's really the only practical way for the OS; using pathnames would be far too complex. So, you will need to call CreateFile . At that point, just request exclusive access.

Why doens't the CreateFile()'s exclusive flag achieve this? It looks like you don't need anything fancy. If your library opens the file with CFile::shareDenyRead and CFile::shareDenyWrite, no other process can read your files as long as they are open by your library.

What you're asking can't be done.

Because exclusive access is granted per handle, not per process, if you open a file with exclusive access once, every subsequent attempt to open it will fail, even if it is from the same process. Exclusive access here means your handle is the only valid one, not that only your process can access it.

So even if you lock a file, your lib won't be able to open it, so it's useless to you. The only way is to lock a file and pass the handle to your lib, which you can't do because your lib wants a filename. Likewise you can't lock the file once it's open by the lib because it won't give you the handle. If you don't have access to the source code of the lib, you're stuck.

You possibly could try something with user permissions, having you're process run from it's own user account and changing the ownership of the files you're about to modify and then changing it back when you're done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM