How does apt-get use /var/cache/apt/archives/lock?

Solution 1:

Short answer is that apt is using fcntl to control lock files.


Depend on what you are doing different locks will be created by apt, let's consider sudo apt update which apt-pkg/update.cc is responsible of, and runs this condition before actually updating our sources lists:

if (Fetcher.GetLock(_config->FindDir("Dir::State::Lists")) == false)

Note that _config->FindDir("Dir::State::Lists") will return: /lists, you can find this out by running:

$ apt-config dump | grep lists
Dir::State::lists "lists/";

So GetLock() will creates a lock file in /var/lib/apt/lists/, and if I run an other sudo apt update process I'll get:

Reading package lists... Done
E: Could not get lock /var/lib/apt/lists/lock ...
E: Unable to lock directory /var/lib/apt/lists/

GetLock() itself lives here in apt-pkg/contrib/fileutl.cc:

Let's have a look at its comment:

// GetLock - Gets a lock file                       /*{{{*/
// ---------------------------------------------------------------------
/* This will create an empty file of the given name and lock it. Once this
   is done all other calls to GetLock in any other process will fail with
   -1. The return result is the fd of the file, the call should call
   close at some time. */

So next time when I run apt update this function instead of creating the lock file will returns -1 and our condition fails and we receive an error.

If we look into the codes of GetLock we can see that it's using fcntl to provide its functionalities.

Basically fileutl.cc is a file utility containing two main function, which defines GetLock as "dpkg compatible lock file manipulation" method.

fcntl itself provides a bunch of system calls to manipulate file descriptors. One of the functionalities which is being provided by fcntl is "POSIX record locks, also known as process-associated locks":

man 2 fcntl

And I'm sure you already know the idea behind using lock files, but to make sure everyone who comes here knows about it:

What is the purpose of lock file?

Solution 2:

Apt and dpkg use lockfiles (in /var/lib/, not /var/cache) to ensure that package management actions and the package database are correctly in sync.

This means that if you install or remove the a package (like the hello package), the package database will be accurate, and your package manager will properly show the correct status of the package.

There are several possible solutions to ensure that package management actions and the package database are in sync. Lockfiles are the solution that the apt developers have chosen...mostly because it is a solution that is simple, easy to troubleshoot, and easy to understand.