问题
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