text: I am writing a script to do some apt commands, but I am running into potential issues of the apt/dpkg databases being locked so my script bails. I want to check the lock files (i.e. /var/lib/dpkg/lock) before doing anything just like apt does when it runs it's command, but I can't figure out how apt is performing the lock.
  The lock file is always there, and apt-get is not doing a flock on the file. How else would it be checking to see if it is in use? From an strace I see that apt-get opens the file, but that is it. In my script, I can open the file while apt-get has it open as well.
  I found out that apt is using a fcntl. Since I am using Ruby for the scripting language, I had to create my own function to look for lock. The reason for this, is because Ruby does not implement the fcntl function entirely. It only provides the function call and constants. The ability to build flock structs and how to pass them is left out or not documented.
  Here is the list I found talking about that.
  Here is the function I ended up writing:
  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
  Well I thought there would be a simple answer here but I can't find anything. First, are you 100% sure that lock file is always there? Try running
  lsof /var/lib/dpkg/lock
  as root to see if any process has it open.
  From what I've read, apt-get does an fcntl lock, but I haven't looked at the code to verify. I guess that wuld explain why the file is there all the time, apt just locks it as needed.
  What about just doing a check of the process list when your script runs, and exiting if apt is running at the same time? Would that be sufficient for your use?
  Looks like this person went down the same path as you did, without much