How to get a process exclusive lock on a folder in Windows? - windows

Is it possible to lock a directory in Windows so as to ensure that no other process is reading or modifying files inside the directory for the duration of the lock, while at the same time allowing the process with the lock to modify and move files and directory itself freely?

This is not a real answer, but as a workaround:
Move the directory to a subdirectory specific to your application, which is on the same volume.
Advantages:
Prevents users and other programs from modifying the file at the old location, as the files will no longer be there
Importantly, will fail if a process already has a file open within that directory, thus ensuring that the "acquired" lock is indeed "exclusive"
Disadvantages:
It's a hack
The software will need to be adapted to work with the directory at a different path than where it was initially
Users and programs attempting to access the files will encounter unusual behavior or errors ("Path not found" instead of "Access denied")
Does not protect against programs that may poke into your application-specific subdirectory
Will leave the directory "locked" (moved to a location the user probably can't find) if your program crashes while the "lock" is "held"

Related

Folders created by Program causes read-only to appear

So, I stumbled across a little problem, I can't seem to figure out.
I have a NAS where I dump data on and a script to download files I need back to my PC.
While doing so, it creates a folder for the file. After that, I run a different script that encodes the video files to save some space.
However, for some reason, the files and folders keep getting a 'read-only' lock that prevents the source file to be deleted after compression.
So I have to get into each individual folder and remove the read-only permission.
Is there some way to disable the read-only lock?
The Owner if the Root folder is my personal account, with full access.
Changing it to SYSTEM or Admin with full access doesn't change anything.

Deleting a locked file created with TempFile

I have a GUI (lxn/walk) app patcher that downloads a file via ftp, streams it to a temporary file and extracts the contents to update the local files. The remove file command is deferred.
This works unless the user exits the program while the file is downloading, then the file isn’t deleted.
I tried to fix this by doing a graceful exit by catching the signal and removing the file there. But unfortunately it throws an error that the file can’t be deleted because it is being used by another program. Which makes sense because the another program is actually itself still writing to the temporary file.
Now I’m stuck and don’t know what to do to make sure that the temporary file is automatically gone once the patcher is not running. How do I do that correctly?
The file could also be created as a normal file, not just a temp file. I would just like to ask too, where in windows is best to write a temporary file?
Now I’m stuck and don’t know what to do to make sure that the temporary file is automatically gone once the patcher is not running. How do I do that correctly?
There are no guaranteed ways to accomplish this as many things beyond the control of the application can cause it to exit. A power failure or kernel panic due to some hardware issue can crash the machine or force it to be restarted.
A strategy that is in common use is to implement a check on program startup for the status of the previous run. Some applications create a lock file at start and remove it on graceful exit. If this lock file exists when the program is restarted, this means the previous run did not result in a clean exit, and the application can take any corrective action. The exact action to be taken depends on the nature of the application, some refuse to start, others give warnings to users.
I would just like to ask too, where in windows is best to write a temporary file?
Each OS has its own location for temporary files. If you eliminate the dir argument to TempFile, it will create it in the appropriate location, as mentioned in the documentation:
TempFile creates a new temporary file in the directory dir, opens the
file for reading and writing, and returns the resulting *os.File. The
filename is generated by taking pattern and adding a random string to
the end. If pattern includes a "*", the random string replaces the
last "*". If dir is the empty string, TempFile uses the default
directory for temporary files (see os.TempDir). Multiple programs
calling TempFile simultaneously will not choose the same file. The
caller can use f.Name() to find the pathname of the file. It is the
caller's responsibility to remove the file when no longer needed.
From os.TempDir we see the following:
On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On
Windows, it uses GetTempPath, returning the first non-empty value
from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On
Plan 9, it returns /tmp.
The directory is neither guaranteed to exist nor have accessible
permissions.

Deleting a directory under Windows in a race-free manner?

http://code.google.com/p/guava-libraries/issues/detail?id=365 discusses the potential race-conditions that may occur while deleting a directory recursively.
According to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7148952 this can be implemented in a race-free manner under Linux using openat(). Is there an equivalent mechanism under Windows?
A key difference between Windows filesystem behavior and linux filesystem behavior is locking and reference counting.
In Windows if a process has a file open, then that file and the path leading to that file are protected.
So, if somebody has "C:\a\b\c\d\file.txt" open, then nobody is allowed to rename or delete any part of the path "C:\a\b\c\d\file.txt".
The linux model is much different, any part of that path can be changed and even the file can be deleted. The process holding the handle to "file.txt" still has a reference, and the file wouldn't be removed from the filesystem until all handles are closed.
The Win32 API doesn't expose a direct way to hold a handle to a directory (though, there are APIs for this - see the "Zw" functions, FindFirstFile may I'm not sure, the backup APIs, etc) - but your process "current directory" does hold a handle for that directory.
Thus, you can get "openat" behavior by changing your working directory and then opening the file directly. Better would be to use something like ZwCreateFile() to open a handle to the directory - since the "current dir" is process global.
Search Stackoverflow and Microsoft.com for ZwCreateFile information.

Invisible hardlink

I have a small application that displays the contents of a log file, somewhat transmogrified for readability. As the log file gets rewritten occasionally and Windows file system semantics prohibit deletion of open files, I create a hardlink to the file.
Obviously, this needs to happen on the same file system as the original file -- at present, I create the harddisk in the same directory, which I believe can be reasonably assumed to fulfill this requirement; the result is that a temporary file shows up in the directory listing where the user just clicked to open the file, which is ugly.
Is there a way to create a hardlink so that it does not show up (the customer where the program is used has several junctions in their directory tree, so it cannot be assumed that a specific directory is on the same filesystem), or is there a better method to read a file that another process may want to delete and rewrite (e.g. by catching their access and closing the file before letting the other process's access go through), so the program can be used on archived (readonly) log files without modification?
No
It won't help if you could. Sharing spans links.
Use the solution posed by Hans Passant as a comment.

Win32 current directory, locking & shell integration

In Win32, your main thread's current working directory is set to the location the executable was launched from. My problem is that even after a call to SetCurrentDirectory() to somewhere else, the process apparently still has a filesystem object referencing this initial startup directory (verifiable with a tool like Process Explorer) - which means this director cannot be deleted by the process.
Does anybody here know of a not-too-hacky solution? I'm specifically running into the problem with a program that integrates with explorer (adding a verb to HKCR\Directory\shell registry key), I need to process files in a right-clicked directory and the remove the source directory, which is impossible because the initial working directory is set to, you guessed it, the right-clicked directory.
EDIT: I'll go for the "use helper launch-from-sane-directory" approach. It might not be super elegant, but it will work and doesn't require any nasty hacks.
Your easiest solution may be to just spawn a little helper process that runs in whatever directory you specify (c:\, e.g.) and then just exit and let it do its thing. It may need to be synchronized with a mutex, or perhaps just retry two or three times on a timer...
I had another thought: You may be able to use CreateFile() with FILE_FLAG_DELETE_ON_CLOSE. Then it should go away when everyone lets go of it, but only if it was opened with FILE_SHARE_DELETE.

Resources