Karthi1234 Karthi1234 - 5 months ago 23
Ruby Question

ruby file execute lock to avoid multiple process for the same script

In my ruby script I have put below code to make sure the same script should not be executed again parallel when another process is already running.

if $0 == __FILE__
if File.new(__FILE__).flock(File::LOCK_EX | File::LOCK_NB)
if RbConfig::CONFIG['host_os'].include? 'linux'
elsif RbConfig::CONFIG['host_os'].include? 'mingw'
elsif RbConfig::CONFIG['host_os'].include? 'solaris'


But its not working as expected on Windows. I have initiated one process and when I run initiate another process on another powershell session its still running instead of coming out.

Any suggestion pls.

Answer Source

Ruby's File class is mostly a thin layer on top of POSIX. As a result, several methods either don't work or behave differently on non-POSIX platforms. This is explicitly acknowledged in the documentation, e.g. the method you are using says:

Not available on all platforms.

It is also implementation-dependent. E.g. JRuby went through the trouble to develop a full POSIX compatibility layer for Java, and as a result, on Windows, JRuby actually is more conforming with Ruby than "Ruby" (i.e. YARV) is!

Long story short: File#flock is just a thin layer on top of POSIX's flock function, and that function simply doesn't exist on Windows. Note that Windows does support file locking using the LockFile Windows API function. However, it doesn't support POSIX file locking. (Except maybe in a POSIX emulation environment such as Mirosoft Services for Unix, MSYS, or Cygwin.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download