Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use filesystem as semaphore

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.

like image 956
Luke101 Avatar asked Dec 05 '25 14:12

Luke101


1 Answers

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.

like image 79
Steve Avatar answered Dec 07 '25 22:12

Steve