如何使用文件系统作为信号量

时间:2013-01-08 23:36:06

标签: vbscript clipboard

我有几个脚本试图访问剪贴板。只有一次一个脚本可以一次访问剪贴板。我的解决方案不起作用。这是我实施的解决方案

  • 检查clipboardLock.txt是否存在。
  • - 如果它不存在则创建它
  • - 做流程
  • - 如果确实存在,则等待3秒至10秒并检查是否存在

这不起作用,因为两个脚本试图创建文件并出错。有技术可以保证只有一个脚本可以访问剪贴板吗?此外,我无权访问数据库。

2 个答案:

答案 0 :(得分:4)

不要让脚本创建文件,而是让它们以独占模式打开现有文件(也就是说,没有其他人可以打开它)。如果文件打开,则可以继续处理,否则脚本必须等待。

要以独占方式打开文件,您可以使用OpenTextFile将其打开以进行编写:

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Set MyFile = fso.OpenTextFile(FileName, ForWriting)

处理完成后,请关闭该文件,以便其他脚本可以尝试打开该文件。

答案 1 :(得分:0)

使用您的方法,vbscript不会阻止ForWriting并等到文件关闭。启动以下脚本两次...首先离开msgbox" File Open ..."打开...然后再次启动。您将获得"权限被拒绝"第二个脚本将会中断。 On Error Resume Next将在继续之前取消等待文件可用的目标。

Const ForReading = 1, ForWriting = 2, ForAppending = 8 
Set filesys = CreateObject("Scripting.FileSystemObject") 
Set filetxt = filesys.OpenTextFile("c:\somefile.txt", ForWriting, True) 
wscript.echo "File Open..."
filetxt.Close
wscript.echo "Done..."

所以我看到有4个赞成票......这怎么可能有用?

这是一个工作程序 - 只需在循环中坐下,直到文件可用:

lockFile

sub lockFile ()
    Dim fso, LockFile, LockFileName, done
    Const ForWriting = 2

    LockFileName = "C:\somefile.lck"
    Set filesys = CreateObject("Scripting.FileSystemObject") 
    done = false
    on error resume next 'need to evaluate error 

    while (not(done))
        err.clear
        Set filetxt = filesys.OpenTextFile(LockFileName, ForWriting, True) 
        if (err.number = 0) then 
            done = true
        else
            done = false
        end if
        wscript.echo "Error [0=file open, 70=file in use] : " & err.number
        wscript.sleep(1000) 'wait one second instead of chewing up CPU
    wend

    wscript.echo "File Open..."
    filetxt.Close
    wscript.echo "Done..."

    on error goto 0 'reset error level

end sub