如果該文件被另一個進程鎖定,則無法將其打開。期。
Windows有專門用於構建備份客戶端的Volume Shadow Copy服務(VSS)。它有複製鎖定文件的規定,確保一致的快照等。API有點複雜,但如果您想要強大的備份解決方案,則沒有其他辦法。
有關使用VSS的示例,您可以查看開放源代碼的HoboCopy備份工具。
編輯:經過一些谷歌搜索後,我發現了兩個例子,做你想做的。我無法保證這些工作,但至少看起來似乎合理。
第一個例子,清晰和良好註釋(語言是基本的一些方言,但很可讀):
$include "windowssdk.inc"
$include "ntddk.inc"
$include "undocumented.inc"
$include "stdio.inc"
$use "_crtdll.lib"
'-------------------------- example
$include "shlwapi.inc"
$define REPLACE_ALWAYS
' open youtube in internet explorer, watch any video (should be downloaded in 100%)
' then run this program to copy the locked fla***.tmp file from your TEMP directory
istring tmppath[MAX_PATH]
' 1. enumerate fla*.tmp files in TEMP directory
ExpandEnvironmentStrings("%TEMP%\\", tmppath, MAX_PATH)
int pathlen = len(tmppath)
strcpy(&tmppath[pathlen], "fla*.tmp")
UINT hFind = findopen(tmppath)
int nFilesFound = 0
int nFilesCopied = 0
if (hFind)
istring name[256] = findnext(hFind)
while (name[0] <> 0)
strncpy(&tmppath[pathlen], name, MAX_PATH-pathlen)
' tmppath = local path to flash video
' 2. copy the file with renamed extension (supported by media player classic)
istring newpath[MAX_PATH]
newpath = tmppath
PathRenameExtension(newpath, ".flv")
' check if we can open the file directly
HANDLE hFile = CreateFile(tmppath, GENERIC_READ, FILE_SHARE_READ _
| FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, 0, 0)
if (hFile <> INVALID_HANDLE_VALUE)
' file opened, so you can copy it with your favorite file manager
CloseHandle(hFile)
else
nFilesFound++
' the file is opened with exclusive access, call the subroutine below to open it
HANDLE hProcess
hFile = OpenFileEx(tmppath, &hProcess)
if (hFile = INVALID_HANDLE_VALUE)
' failed
MessageBox 0, "failed to open " + tmppath, ""
else
' copy it now ...
$ifdef REPLACE_ALWAYS
HANDLE hOutFile = CreateFile(newpath, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0)
$else
HANDLE hOutFile = CreateFile(newpath, GENERIC_WRITE, 0, 0, CREATE_NEW, 0, 0)
$endif
if (hOutFile = INVALID_HANDLE_VALUE)
' failed ?
MessageBox 0, "failed to create " + newpath, ""
else
' ... but first suspend the owner process (because the handle is duplicated, and
' if the owner process changes file pointer, it will be reflected also in this process)
declare import, NtSuspendProcess(HANDLE hProcess), NTSTATUS
declare import, NtResumeProcess(HANDLE hProcess), NTSTATUS
NtSuspendProcess(hProcess)
' save original file pointer in originalFilePos variable
LARGE_INTEGER originalFilePos
LARGE_INTEGER nullFilePos
nullFilePos.QuadPart = 0q
SetFilePointerEx(hFile, nullFilePos, &originalFilePos, FILE_CURRENT)
' seek to beginning
SetFilePointerEx(hFile, nullFilePos, NULL, FILE_BEGIN)
' copy, using string name as the buffer
DWORD BytesRead, BytesWriten
while (ReadFile(hFile, &name, 256, &BytesRead, 0) and BytesRead)
WriteFile(hOutFile, name, BytesRead, &BytesWriten, 0)
endwhile
'
nFilesCopied++
' restore file pointer
SetFilePointerEx(hFile, originalFilePos, NULL, FILE_BEGIN)
' cleanup
CloseHandle(hOutFile)
' resume the process
NtResumeProcess(hProcess)
endif
CloseHandle(hFile)
endif
endif
name = findnext(hFind)
endwhile
findclose(hFind)
endif
if (MessageBox(0, using("Copied # from # locked .FLV files. Open Directory ?", nFilesCopied, nFilesFound), "", MB_YESNO) = IDYES)
tmppath[pathlen-1] = 0
system tmppath
endif
'-------------------------- code
type SYSTEM_HANDLE_ENTRY
ULONG OwnerPid
BYTE ObjectType
BYTE HandleFlags
USHORT HandleValue
PVOID ObjectPointer
ACCESS_MASK GrantedAccess
endtype
type SYSTEM_HANDLE_INFORMATION
ULONG HandleCount
SYSTEM_HANDLE_ENTRY Handles[1]
endtype
type MY_OBJECT_TYPE_INFORMATION
OBJECT_TYPE_INFORMATION t
iwstring buffer[64]
endtype
type MY_OBJECT_NAME_INFORMATION
OBJECT_NAME_INFORMATION t
iwstring buffer[280]
endtype
declare import, NtQuerySystemInformation(_
int SystemInformationClass,_
PVOID SystemInformation,_
ULONG SystemInformationLength,_
pointer ReturnLength),NTSTATUS
const SystemHandleInformation = 16
sub OpenFileEx(string path, pointer pphProcess),HANDLE
MY_OBJECT_TYPE_INFORMATION htype
MY_OBJECT_NAME_INFORMATION name
*<HANDLE>pphProcess = 0
HANDLE h = INVALID_HANDLE_VALUE
' convert c:\ to \Device\HardDiskVolume...
' 1. extract partition letter
iwstring root[4]
root[0] = path[0], 58, 0
' 2. convert it to \Device\HardDiskVolumeX
iwstring wszNTPath[280]
int cch = QueryDosDeviceW(root, wszNTPath, 280)
if (!cch) then return INVALID_HANDLE_VALUE
' 3. append remaining folders and file name from string path parameter
' so <path> "c:\Program Files" gets converted to <wszNTPath> "\Device\HardDiskVolume1\Program Files"
cch = wcslen(wszNTPath)
_snwprintf(&wszNTPath[cch], 280-cch, L"%S", &path[2])
' now get the list of all handles, and find the handle which name is equal to wszNTPath
ULONG BytesNeeded, BufferSize = 4096
pointer handles = new(char, BufferSize) ' SYSTEM_HANDLE_INFORMATION*
while (handles)
' get the list of all user-mode handles
NTSTATUS status = NtQuerySystemInformation(SystemHandleInformation, handles, BufferSize, &BytesNeeded)
if (status = STATUS_INFO_LENGTH_MISMATCH)
' BytesNeeded is not adjusted, so we need to increase buffer size
delete handles
BufferSize += 32768
handles = new(char, BufferSize)
elseif (!status)
settype handles, SYSTEM_HANDLE_INFORMATION
' sort handles by owning process id
qsort(&*handles.Handles, *handles.HandleCount, len(SYSTEM_HANDLE_ENTRY), &SortHandlesCb)
pointer node = *handles.Handles
settype node, SYSTEM_HANDLE_ENTRY
ULONG OwnerPid = 0
HANDLE hProcess = 0
HANDLE hThisProcess = GetCurrentProcess()
BYTE ObjectTypeFile = 0
while (*handles.HandleCount)
*handles.HandleCount--
if (*node.GrantedAccess & FILE_READ_DATA) ' 13019F
if (OwnerPid <> *node.OwnerPid)
OwnerPid = *node.OwnerPid
if (hProcess) then CloseHandle(hProcess)
hProcess = OpenProcess(PROCESS_DUP_HANDLE|PROCESS_SUSPEND_RESUME, FALSE, OwnerPid)
endif
if (hProcess)
HANDLE hObject
if (DuplicateHandle(hProcess, *node.HandleValue, hThisProcess, &hObject, 0, FALSE, DUPLICATE_SAME_ACCESS))
if (GetFileType(hObject) = FILE_TYPE_DISK)
if (!ObjectTypeFile) ' query object type name as "integer"
if (!NtQueryObject(hObject, ObjectTypeInformation, &htype, len(htype), &BytesNeeded))
if (!_wcsnicmp(htype.t.TypeName.Buffer, L"File", 4))
ObjectTypeFile = *node.ObjectType
endif
endif
endif
' do not query object name with granted access 0x0012019f (deadloock)
if (ObjectTypeFile and (ObjectTypeFile = *node.ObjectType) and (*node.GrantedAccess <> 0x0012019f))
' query file name
if (!NtQueryObject(hObject, ObjectNameInformation, &name, len(name), &BytesNeeded))
if (name.t.Name.Buffer and !wcsicmp(name.t.Name.Buffer, wszNTPath)) ' compare
*<HANDLE>pphProcess = hProcess
delete handles
return hObject
endif
endif
endif
endif
CloseHandle(hObject)
endif
endif
endif
node = &*node[1]
endwhile
if (hProcess) then CloseHandle(hProcess)
delete handles
else
' NtQuerySystemInformation failed
delete handles
endif
endwhile
if (handles) then delete handles
return h
endsub
declare cdecl SortHandlesCb(SYSTEM_HANDLE_ENTRY p1, SYSTEM_HANDLE_ENTRY p2),int
sub SortHandlesCb(SYSTEM_HANDLE_ENTRY p1, SYSTEM_HANDLE_ENTRY p2),int
if (p1.OwnerPid = p2.OwnerPid) then return 0
if (p1.OwnerPid > p2.OwnerPid) then return 1
return -1
endsub
另一個凌亂的例子是在http://forum.sysinternals.com/topic7974.html。
請注意,這兩個示例都使用Native API函數及其某些未公開的功能。
的基本步驟是:
- 獲取文件句柄值被鎖定過程觀察。這通過調用
NtQuerySystemInformation
來獲得系統中所有句柄的列表和NtQueryObject
來找到具有匹配文件名的句柄。 請注意,文件名必須轉換爲NT設備格式。
- 打開擁有擁有足夠特權(
PROCESS_DUP_HANDLE
和PROCESS_SUSPEND_RESUME
)的句柄(OpenProcess
)並調用DuiplicateHandle
(將該流程作爲源,處理來自步驟1的值以及將流程作爲目標)的過程。
- 使用
NtSuspendProcess
「暫停」進程並阻止它修改文件指針和文件內容)。
- 使用重複句柄複製文件。
- 恢復文件指針,關閉句柄,調用
NtResumeProcess
來取消暫停進程。
EDIT2:我個人已經用另一種方式來訪問鎖定的文件 - 帶手動NTFS解析原始磁盤訪問。例如。鑑於文件名稱找到它的MFT條目,解碼數據運行位置並從原始磁盤讀取它們。原始磁盤訪問始終可用(只要您具有管理員權限),因此任何文件都是可讀的。缺點是零一致性保證,所以它不適合用於備份目的。
PS。如果我是你,我仍然會使用官方支持的VSS。備份軟件不應該依賴黑客。
即使不使用fopen我使用CreateFile? –
@布魯諾你使用的任何方法。他們都最後調用CreateFile。 –
對不起,但我剛剛閱讀有關duplicateHandle(),是否能夠複製進程句柄,然後使我能夠使用其他進程正在使用相同的文件? –