【问题标题】:Exclusively Locked File Detection AutoIt独占锁定文件检测 AutoIt
【发布时间】:2011-10-24 13:22:24
【问题描述】:

如何检查文件是否在 AutoIt 中被独占锁定?我不是在谈论读/写访问。另外,我做了一些研究,如果文件被锁定,它不会出现在任务管理器进程列表中。

一个例子是在 Perl 中称为flock: 您通过 $theRC = flock($HANDLE, LOCK_EX|LOCK_NB); 来检查文件是否被锁定

我正在尝试在 AutoIt 中复制它。

我找到了一种可行的解决方案:

Local $f = "C:/log.txt"

MsgBox(0, _FileInUse($f), @error)

;===============================================================================
;
; Function Name:    _FileInUse()
; Description:      Checks if file is in use
; Parameter(s):     $sFilename = File name
; Return Value(s):  1 - file in use (@error contains system error code)
;                   0 - file not in use
;
;===============================================================================
Func _FileInUse($sFilename)
    Local $aRet, $hFile
    $aRet = DllCall("Kernel32.dll", "hwnd", "CreateFile", _
                                    "str", $sFilename, _ ;lpFileName
                                    "dword", 0x80000000, _ ;dwDesiredAccess = GENERIC_READ
                                    "dword", 0, _ ;dwShareMode = DO NOT SHARE
                                    "dword", 0, _ ;lpSecurityAttributes = NULL
                                    "dword", 3, _ ;dwCreationDisposition = OPEN_EXISTING
                                    "dword", 128, _ ;dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL
                                    "hwnd", 0) ;hTemplateFile = NULL
    $hFile = $aRet[0]
    If $hFile = -1 Then ;INVALID_HANDLE_VALUE = -1
        $aRet = DllCall("Kernel32.dll", "int", "GetLastError")
        SetError($aRet[0])
        Return 1
    Else
        ;close file handle
        DllCall("Kernel32.dll", "int", "CloseHandle", "hwnd", $hFile)
        Return 0
    EndIf
EndFunc

【问题讨论】:

  • 呸,autoit 没有语法机器人?
  • 突出显示您的代码并单击编辑器工具栏中的{} 图标。

标签: autoit


【解决方案1】:

这应该可以解决问题:

Func FileInUse($filename)
    $handle = FileOpen($filename, 1)

    $result = False
    if $handle = -1 then $result = True

    FileClose($handle)

    return $result
EndFunc

;~ usage
$filename = "C:\Windu15f.exe"
if FileInUse($filename) Then
    MsgBox(0, "", "File is in use")
Else
    MsgBox(0, "", "Not in use - go nuts")
EndIf

【讨论】:

  • 实际上,Windows/NTFS(不确定是哪个)允许不同的程序同时打开同一个文件的句柄。如果你可以通过 FileOpen 获得这个锁,其他程序仍然可以以读取模式打开文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
  • 2013-03-15
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 2021-03-19
相关资源
最近更新 更多