Ubuntu may suddenly display an error that is hard to decipher at first glance: the system will tell you that it cannot set and/or acquire the lock “/var/lib/dpkg/lock” when installing or updating a package (whether with apt-get, aptitude, USC, GDebi, dpkg or aptURL), preventing you from using the entire packaging system until you restart the system.
What does this mean? The entire .deb installer system in Raspbian — essentially dpkg, which underpins everything — is designed so that installation, removal, update and other operations take place strictly one at a time, ruling out any possibility of dependency conflicts, version conflicts and half-finished installations that could compromise the stability and reliability of the system. When one of these operations starts, dpkg tries to create a file — specifically in /var/lib/dpkg — called lock, whose purpose is to signal that “a package operation is in progress and no others can be started”. If this file already exists, dpkg automatically assumes another package operation is in progress, stops, and displays an error message.
There are essentially two possible causes of this problem:
- You are trying to install/remove/update packages while another such operation is already running on the system (e.g. you try to use apt-get while downloading system updates with the graphical tool);
- a previous installation/removal/update did not complete successfully because of a sudden program freeze, a temporary system crash or some other “hitch”;
As you might imagine, solving the problem in the first case is fairly simple: you just need to wait for the previous operation to finish (for the reasons explained above) and then start a new one. Please note: do not force the previous operation to stop, otherwise you may end up straight in the second case.
In the second case, things get a little more complicated: there are cases where restarting the system fixes everything, but there are also cases where restarting the system is not enough to fix things. And besides… restarting the computer for something like this is a real nuisance. There is a solution: simply delete the file manually and make the dpkg database consistent again.
A word of caution: use this method very sparingly and, before proceeding, check that there really are no other installations in progress!
First, delete the lock file with the command
sudo rm /var/lib/dpkg/lock
Now rebuild the dpkg database with the command
sudo dpkg --configure -a
And clean up any traces of half-finished installations/unresolved dependencies (if any remain) with the command
sudo apt-get -f install
The problem will now be solved, and you can resume updating or installing new packages on the system.
Enjoy!
