How to use filesystem as semaphore

妖精的绣舞 提交于 2019-12-14 03:48:53

问题


I have several script trying to access the clipboard. Only, one script at a time can access the clipboard at a time. My solution did not work. Here is the solution I implemented

  • check if clipboardLock.txt exists.
  • -if it does not exist then create it
  • --do processes
  • -if it does exist then wait 3 seconds to 10 seconds and check if it exists

This did not work well because two scripts tried to create the file and errored out. Is there a technique to guarantee only one script can access the clipboard? Also, I do not have access to a database.


回答1:


Instead of having the scripts create a file, have them open an existing file in exclusive mode (that is, no one else can open it). If the file opens processing can proceed, otherwise the script must wait.

In order to open the file exclusively, you can use OpenTextFile to open it for writing:

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

Once the processing is complete, close the file so that other scripts can attempt to open the file.




回答2:


Using your method, vbscript does not block on ForWriting and wait until the file is closed. Launch the following script twice ... first leaving the msgbox "File Open..." open ... then launch again. You'll get "Permission Denied" and the second script will break. On Error Resume Next will defeat the objective of waiting for the file to become available before proceeding.

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..."

So I see there are 4 upvotes ... how did this possibly work?

Here's a working routine - just sit in while loop until the file becomes available:

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


来源:https://stackoverflow.com/questions/14225922/how-to-use-filesystem-as-semaphore

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