Skip to content

Instantly share code, notes, and snippets.

@gondoi
Created January 13, 2011 19:42
Show Gist options
  • Save gondoi/778459 to your computer and use it in GitHub Desktop.
Save gondoi/778459 to your computer and use it in GitHub Desktop.
function to check for a read or write lock
require 'fcntl'
class File
def flocked? &block
flockstruct = [Fcntl::F_RDLCK, 0, 0, 0, 0].pack("ssqqi")
fcntl Fcntl::F_GETLK, flockstruct
status = flockstruct.unpack("ssqqi")[0]
case status
when Fcntl::F_UNLCK
return false
when Fcntl::F_WRLCK|Fcntl::F_RDLCK
return true
else
raise SystemCallError, status
end
end
alias_method "if_not_flocked", "flocked?"
end
dpkg = open("/var/lib/dpkg/lock")
if dpkg.flocked?
p "it's locked"
else
p "not locked"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment