Skip to content

Instantly share code, notes, and snippets.

@thbar
Created March 27, 2012 14:25
Show Gist options
  • Select an option

  • Save thbar/2216359 to your computer and use it in GitHub Desktop.

Select an option

Save thbar/2216359 to your computer and use it in GitHub Desktop.
Single instance check with ruby and windows
# 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
@nrk

nrk commented Mar 27, 2012

Copy link
Copy Markdown

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-mutex gem and a global mutex, see this gist. I'm not sure if win32-mutex has 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.

@thbar

thbar commented Mar 27, 2012

Copy link
Copy Markdown
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 :)

@nrk

nrk commented Mar 27, 2012

Copy link
Copy Markdown

@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:-)

@thbar

thbar commented Mar 27, 2012

Copy link
Copy Markdown
Author

@nrk sure :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment