Created
March 27, 2012 14:25
-
-
Save thbar/2216359 to your computer and use it in GitHub Desktop.
Single instance check with ruby and windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # context: I need to be reasonably sure that not two instances of a ruby script | |
| # run at the same time, on Windows. What follows seems to work. | |
| # tested on ruby 1.9.3p125 (2012-02-16) [i386-mingw32] | |
| def log(msg) | |
| puts "#{$$} #{msg}" | |
| end | |
| def do_the_work_with_lock | |
| File.open("test.lock", File::RDWR|File::CREAT, 0644) {|f| | |
| log "Attempting to lock..." | |
| if (f.flock(File::LOCK_EX | File::LOCK_NB) == false) | |
| log "Another instance is already running! Exiting" | |
| abort | |
| end | |
| log "Lock acquired" | |
| f.rewind | |
| f.write($$) | |
| f.flush | |
| 10.times do |i| | |
| log "Doing work... #{i}" | |
| sleep(1) | |
| end | |
| log "Exiting" | |
| sleep(1) | |
| } | |
| end | |
| do_the_work_with_lock |
Author
@nrk thanks for sharing this! Didn't think about using win32-mutex. Looks like a release occurred recently (0.3.2) so my guess is that this is still likely to work on Ruby 1.9.
Good to know :)
@thbar to be honest I've never tried that script to check the state of processes running under different users sessions since I just needed to ensure that only one instance was running inside the same user session, so you probably might want to test this condition just to make sure that it meets your requirements:-)
Author
@nrk sure :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Years ago (there still was Ruby 1.8.6 with the OneClick Installer) I tried to achieve the same thing but by using the
win32-mutexgem and a global mutex, see this gist. I'm not sure ifwin32-mutexhas been updated for 1.9 and can be used with the Ruby Installer though. Mutexes can also be subject to some restrictions due to access rights, but anyway it worked for me.