0

Am trying to lock one executable script to make sure it doesn't run second time when there is another process running. Here is my code,

if $0 == __FILE__
  if File.new(__FILE__).flock(File::LOCK_EX | File::LOCK_NB)
    main()
  end
end

and getting below error,

# ruby /tmp/test.rb
/tmp/test.rb:397:in `flock': Bad file number - /tmp/test.rb (Errno::EBADF)
        from /tmp/test.rb:397:in `<main>'
#

Am using ruby version 1.9.3,

# ruby --version
ruby 1.9.3p551 (2014-11-13 revision 48407) [sparc-solaris2.11]
#

But its working perfect in Linux environments.

Karthi1234
  • 949
  • 1
  • 8
  • 28

1 Answers1

0

Found the solution. In Solaris we need to open file with read/write mode only then the exclusive lock will happen.

if $0 == __FILE__
  if File.new(__FILE__, 'r+').flock(File::LOCK_EX | File::LOCK_NB)
    main()
  end
end
Karthi1234
  • 949
  • 1
  • 8
  • 28