In windows, do file-locks stay after a process was terminated via taskkill?
We are not talking about a reboot/restart here (similar to another question). This question distinguishes the different way that windows handles existing file locks on a taskkill versus the way it responds to a shutdown/reboot.
If I force kill a program, will the files it has locked still remain locked or do the locks get released when the process dies as well?
By force kill, I mean such as using the 'taskkill' command or 'end process tree' in taskmanager.
To further clarify, I am not talking about a process leaving a resident un-removed auxiliary lock file, such as does MS Word. I am talking about the status of an actual exclusive or shared file lock.
Does taskkill release a filelock? Or does the lock stay put until such time as a reboot or an admin user action is taken within the computer management console?
Here is what I can confirm - killing a 16-bit process that places an exclusive lock
This is using a small console program that puts an exclusive lock on a file in the same local directory. The program stays running until the user presses a key and then it will unlock the file. Here is what happens:
If launched at the command-prompt and killed in taskmanager, it does release the lock. The process to kill is the specific cmd.exe that launched the program. Killing it does release the lock.
If launched by clicking and then killed by closing the window, then the lock is released.
However, if launched by clicking and then killing the conhost.exe in taskmanager, it does not release the lock. In this case, there is also no cmd.exe because it was clicked. So the only way to kill it is via killing the conhost.exe or ntvdm.exe it is running in. The lock stays in place until after the reboot.
If launched by clicking and then killing the ntvdm.exe in taskmanager, it does release the lock.
At no time does the exclusive lock actually prevent the file from being deleted. However, windows does not allow the file to be copied in explorer while the lock is in place.
So, two different behaviours depending on whether the task is launched via cmd prompt or via clicking and killing the conhost or ntvdm subsystem. Of course, killing the ntvdm.exe subsystem also kills any other processes being tasked in the ntvdm thread.
Solution 1:
Yes, the locks remain but you cannot predict when they will get released by the OS. See LockFile() and LockFileEx():
If a process terminates with a portion of a file locked or closes a file that has outstanding locks, the locks are unlocked by the operating system. However, the time it takes for the operating system to unlock these locks depends upon available system resources. Therefore, it is recommended that your process explicitly unlock all files it has locked when it terminates. If this is not done, access to these files may be denied if the operating system has not yet unlocked them.