How can I simulate a “locked” file (one which has a write lock)

眉间皱痕 提交于 2019-12-04 09:02:50

问题


I am trying to debug a problem where users occasionally have locked files which they try to open. The code appears to have correct exception handling but users are still reporting seeing error messages. How can I simulate a locked file so that I can debug this myself?

EDIT: For Windows.


回答1:


depends, but in case, MS word locks
if you are wonderig if your application lock files and it do not relase locks:
just modify a bit your aplication (to create a testapp) and never close the file (and keep it runnig)




回答2:


try this:

( >&2 pause ) >> yourfile.txt

>> opens yourfile.txt in append mode

see this for a reference




回答3:


I used LockFileEx function from the Windows API to write a unittest in Python. This worked well for me (shutil.copy() with a locked target fails).

import win32con
import win32file
import pywintypes

p = "yourfile.txt"
f = file(p, "w")
hfile = win32file._get_osfhandle(f.fileno())
flags = win32con.LOCKFILE_EXCLUSIVE_LOCK | win32con.LOCKFILE_FAIL_IMMEDIATELY

win32file.LockFileEx(hfile, flags, 0, 0xffff0000, pywintypes.OVERLAPPED())

See: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203%28v=vs.85%29.aspx



来源:https://stackoverflow.com/questions/5860542/how-can-i-simulate-a-locked-file-one-which-has-a-write-lock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!