Check if file is locked by a process filehandle - c++

Given I have a list of all file handles of all processes, how could I find out which of these handles are actually locking a file?
From what I understand I could simply try to open the files and try to get all the permissions and if something goes wrong I'd know it is locked. But that sound extremely inefficient. I mean I already have the handles is there no way to check which permissions the handles have?
Preferably I'd like to see a solution that works on Windows XP and above.
I already searched through the GetFileInformationByHandleEx function, but I couldn't find anything about access permissions. :/
Edit:
I don't need real-time information on the file lock. The files that I'm planning to work on will either be locked until certain applications are closed or not be locked at all.

This question is a duplicate of Win32 files locked for reading: how to find out who's locking them.
Also, Hans Passant's commentary is correct: querying the locked state of any Win32 file gives stale information. Disregarding this warning will cause hard-to-find bugs.
If you control all bits of code that you think will access the files, it's better to use a named pipe for interprocess communication, instead of querying locked files.

You can use NtQueryObject API to get information about the handle including the following:
ULONG Attributes;
ACCESS_MASK GrantedAccess;
Or you can access the same information using NtQueryInformationFile using FileModeInformation and FileAccessInformation values for FileInformationClass parameter.

Related

File Close Notification

I wish to know when another application finishes editing a file.
I am aware of FindFirstChangeNotification, ReadDirectoryChangesW and the FileSystemWatcher class, however I think these are only able to detect file creation and changes. Which won't allow me to know whether the file still has content which will be written to it in future or not. One solution would be to wait to ensure that all data has been written, but I feel that there should be a better way.
I wish to know when the process writing to the file closes the handle it has, I think writing a File System Filter Driver may allow for this, can anyone confirm? Or provide another method I which I could use. Also I would prefer not to rely on something like .net but I wouldn't rule it out.
Thanks very much, in advance.
You can poll this by trying to open the file in exclusive mode.
On windows you can use OpenFile with OF_SHARE_EXCLUSIVE.

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, i.e. 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.
I've never used them, but LockFile/LockFileEx docs say: Locks the specified file for exclusive access by the calling process.
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.

How lock a file in windows using c++?

How can I lock a file in windows to only current thread (no other threads from same process and no other processes) can access (read/write) the file?
If it is possible please tell me some fcntl-like solution (solution which locks file having its descriptor). But in any case other solutions are welcome too.
In Windows, you can open a file with exclusive access with the API function CreateFile and specifying 0 as the share mode. More details at this MSDN link, and this MSDN link.
Use the WinAPI call LockFile, Here is a example of its use. However this will only protect you from other processes from touching your file, it still lets other threads in the same process use the file.
EDIT:
I did not see this was C++ sorry, I only know the inter thread c# solution, however that MSDN link can at least get you started on preventing other processes from touching your file.

How to determine when files are done copying for further processing?

Alright so to start this is strictly for Windows and I'd prefer to use C++ over .NET but I'm not opposed to boost::filesystem although if it can be avoided in favor of straight Windows API I'd prefer that.
Now the scenario is an application on another machine I can't change is going to create files in a particular directory on the machine that I need to make backups of and do some extra processing. Currently I've made a little application which will sit and listen for change notifications in a target directory using FindFirstChangeNotification and FindNextChangeNotification windows APIs.
The problem is that while I can get notified when new files are created in the directory, modified, size changes, etc it only notifies once and does not specifically tell me which files. I've looked at ReadDirectoryChangesW as well but it's the same story there except that I can get slightly more specific information.
Now I can scan the directory and try to acquire locks or open the files to determine what specifically changed from the last notification and whether they are available for further use but in the case of copying a large file I've found this isn't good enough as the file won't be ready to be manipulated and I won't get any other notifications after the first so there is no way to tell when it's actually done copying unless after the first notification I continually try to acquire locks until it succeeds.
The only other thing I can think of that would be less hackish would be to have some kind of end token file but since I don't have control over the application creating the files in the first place I don't see how I'd go about doing that and it's still not ideal.
Any suggestions?
This is a fairly common problem and one that doesn't have an easy answer. Acquiring locks is one of the best options when you cannot change the thing at the remote end. Another I have seen is to watch the file at intervals until the size doesn't change for an interval or two.
Other strategies include writing a no-byte file as a trigger when the main file is complete and writing to a temp directory then moving the complete file to the real destination. But to be reliable, it must be the sender who controls this. As the receiver, you are constrained to watching the directory and waiting for the file to settle.
It looks like ReadDirectoryChangesW is going to be your best bet. For each file copy operation, you should be receiving FILE_ACTION_ADDED followed by a bunch of FILE_ACTION_MODIFIED notifications. On the last FILE_ACTION_MODIFIED notification, the file should no longer be locked by the copying process. So, if you try to acquire a lock after each FILE_ACTION_MODIFIED of the copy, it should fail until the copy completes. It's not a particularly elegant solution, but there doesn't seem to be any notifications available for when a file copy completes.
You can process the data once the file is closed, right? So the task is to track when the file is closed. This can be done using file system filter driver. You can write your own or you can use our CallbackFilter product.

modify an open file c++

Under Windows is there a way to modify a file/executable opened by another process using c++?
Is there a way to modify an open executable in windows?
No.
Is there a way to modify an open file in windows using c++?
Yes. If it has been opened with the proper share permissions. See http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx FILE_SHARE_WRITE
It may be possible but perhaps not easy to achieve. You need inject thread in destination process and know PE format for correctly edit opened file and modify it.
All information is on web.
Good Luck.
I find this freeware tool, it proposes to unlock files and folders.
The OS holds the executable file open for read-only sharing as long as it's running, so there's no way to modify it directly. You can, however, open it for reading (if you specify read-sharing in your CreateFile call), and make a modified copy of it, while it's running.
I don't know if that's what you had in mind, but if it's your own program you're doing this to, you can start the new copy and have it pick up where the previous one left off... not straightforward, but not all that difficult either.