advait@advait-Bravo-15-A4DDR:~$ sudo apt install ubuntu-restricted-extras
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 43843 (synaptic)
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 43843 (synaptic)
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 43843 (synaptic)
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 43843 (synaptic)
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 43843 (synaptic)
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 43843 (synaptic)
asked Jul 17, 2021 at 11:37
2
Close synaptic package manager, and the «sudo apt install» command will automatically continue.
You cannot have two different applications that work with the APT package management system open at the same time.
Yes, I very frequently see the same messages as you
answered Jul 17, 2021 at 12:32
vanadiumvanadium
80.6k6 gold badges114 silver badges180 bronze badges
0
You can force close the process by using the process id.
If your terminal says,
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 43843 (synaptic)
Then, the process id in your case is 43843.
To kill the process use this command,
sudo kill 43843
answered Mar 30, 2022 at 2:17
ibnɘꟻibnɘꟻ
1434 bronze badges
3
This answer on Unix & Linux SE by Stéphane Chazelas has some useful commands:
If you want to kill processes based on their name or argument list, use pkill.
pkill regexp
Will kill all processes whose name matches the regexp extended regular
expression.pkill -f regexp
Will kill all processes whose list of arguments (including the first which usually contains the command name) concatenated with spaces matches the regexp.
Zanna♦
68.9k56 gold badges215 silver badges327 bronze badges
answered Jan 12, 2022 at 14:24
1
In this tutorial from Linux troubleshooting, we intend to show you How To Fix the Waiting for Cache Lock Error on Ubuntu. I’m trying to install a package on my Ubuntu server, suddenly I am faced with this error: Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. So I decided to show you how to fix this error if you have this trouble.
- Steps To Fix Waiting for Cache Lock Error on Ubuntu
Steps To Fix Waiting for Cache Lock Error on Ubuntu
An error “waiting for cache lock ubuntu var/lib/dpkg/lock-frontend” comes across during the installation of the package. The reason this error occurs is that the package manager is already in use.
The package manager executes some configuration files while installing or removing some packages from the operating system. If dpkg does not properly compile required files due to involvement in installing any other application, the error will occur:
Error
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 1638 (apt)
Now you can follow one of the solutions below to fix the cache lock error.
Kill The Process ID To Fix the Cache Lock Error on Ubuntu
If you get the waiting for cache lock error, you can force close the process by using the process id.
In my case, the process ID is 1638. To kill the process, you can use the following command:
sudo kill 1638
This will resolve your problem.
Waiting for your Running Process
Another way to fix this error is to just wait for the execution of processes that are currently run on Ubuntu. After the completion, you can execute the required command in the terminal.
Remove Lock File on Ubuntu
Another way to tackle the error is possible to remove the “lock-frontend” file that generates the error. These files do not permit change of the system files during the execution of any process (installing or uninstalling packages). To remove the “lock-frontend”, you can use the following command:
sudo rm /var/lib/dpkg/lock-frontend
Then, run the command below to apply the changes:
sudo dpkg --configure -a
Finally, run the system update:
sudo apt update
That’s it.
Conclusion
As we said, the reason this error (Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend) occurs is that the package manager is already in use. To fix it, you can wait for the running process, kill the process by ID, or you can remove the lock file on Ubuntu.
Hope you can resolve your problem with these solutions.
You may be like these articles too:
Fix the Linux Time change After Reboot
Troubleshoot DNS in Linux
The dpkg is a utility to download or install any applications from the Debian repository. The “.deb” package is utilized for downloading any application by specifying the package name. An error “waiting for cache lock ubuntu var/lib/dpkg/lock-frontend” comes across during the installation of the package. The purpose of this guide is to explain all possible solutions to encounter the above-mentioned error.
The content of this article is as below:
- Reason: Package Manager dpkg Already Used
- Solution 1: Wait for Running Process
- Solution 2: Kill Running Process
- Solution 3: Remove the Lock File
Reason: Package Manager dpkg Already Used
The package manager executes some configuration files while installing or removing some packages from the operating system. If dpkg does not properly compile required files due to involvement in installing any other application, the error will generate.
Solution 1: Wait for Running Process
One of the best solutions is to just wait for the execution of processes that are currently run. After the completion, you can execute the required command in the terminal.
Solution 2: Kill Running Process
An alternative solution is also available to stop the running process from generating the error. To display the list of the running processes is possible by following the below procedure:
Display Running Process
The “ps” command is utilized to display the running processes by utilizing the “grep” that matches the pattern which is executing with “apt”. For this, execute the below script:
In our case, you can visualize the list of running processes such as “VLC” has process id “3770” that causes the waiting error.
Or
Also, you can find out the running dpkg packages by following the below script:
Or
Another way to locate the running process id is possible through the “lsof” command. It displays the list of the open files on which the particular process is running:
$ sudo lsof /var/lib/dpkg/lock
Kill Specific Process via ID
To kill the “vlc” process, the “kill” command is utilized with the “-9” signal that kills the running process whose id is “3770”:
You can verify that the “vlc” process whose id “3770” has been successfully killed as seen below:
Solution 3: Remove the Lock File
One of the solutions to tackle the error is possible to remove the “lock-frontend” file that generates the error. These files do not permit change of the system files during the execution of any process (installing or uninstalling packages). To remove the “lock-frontend”, the “rm” command is utilized specifying the path directory:
$ sudo rm /var/lib/dpkg/lock-frontend
Update Debian Package Manager
To apply the changes, execute the below script for updating the Debian package as below:
$ sudo dpkg --configure -a
After executing the above process, update the repository using the root privilege “sudo” via the below command:
That is all from the guide.
Conclusion
The error “waiting for cache lock ubuntu var/lib/dpkg/lock-frontend” occurs due to the involvement of the dpkg package manager in another running process. It can be resolved by waiting for the executing process or killing the running process via process name or PID. This guide will demonstrate all possible solutions to resolve errors in the Ubuntu operating system.
We explain some steps and methods by which you can quickly fix the Could not get lock /var/lib/dpkg/lock error, which is common in Ubuntu Linux.
The Backstory
It happens more than you can imagine. One fine morning you boot up your shiny Ubuntu Linux and try to install something or upgrade your system. And you run into this error – "Could not get lock /var/lib/dpkg/lock ....".
Reason? The reason is simple and happens with the “Advanced Package Tool (apt)“. The apt package tool is busy doing other operations while you asked it to do something. When apt does some package operation, it creates a lock file to prevent this scenario. As per OS principle, a critical resource should be locked while performing system upgrades/updates so that no other process can access it. This is to prevent any unwanted system behaviour.
There are several variations of this error. But the root cause is the same as what I described above.
Here are some of the errors.
Some Sample Errors
E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable) E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?
Waiting for cache lock: Could not get lock /var/lib/dpkg/lock-frontend. It is held by process 10162 (unattended-upgr)
E: Could not get lock /var/lib/apt/lists/lock - open (11: Resource temporarily unavailable)
E: Unable to lock directory /var/lib/apt/lists/
Method 1 (recommended)
The safest and recommended way to fix this is to wait. Since the apt is running in the background, it’s better you wait for a few minutes. And then, you can try to perform the operation. Most of the time, it resolves the issue by letting the system take care of it.
Method 2
The second method is to remove the lock file manually. This requires admin privileges. Open a terminal prompt and run the following command to clear the lock.
After you run the command, try to perform the operation which caused the error. And you should be fine.
sudo rm -f /var/lib/dpkg/lock
Method 3
The third method is to manually find the process ID of apt, holding the lock and terminate it.
You can filter all the processes which have apt using the command below.
ps aux | grep apt
Once you do that, you can get the process ID (2nd column in the above image) and kill it using the following sample command.
kill -9 processnumber
Method 4
The fourth method is to disable the daily auto update check timer systemd service to try your operation. To do that, open a terminal and disable the service using the following command.
sudo systemctl stop apt-daily.timer
Now, reboot the system and try your operation. If you are all set and the error is gone, you can enable the timer service again using the following command. And you should be all set.
sudo systemctl start apt-daily.timer
Method 5
The final method is specific to additional errors which come with apt lock file.
If the error contains a line like – “E: Unable to lock directory /var/lib/apt/lists/”, then try the following command.
sudo rm /var/lib/apt/lists/* -vf
Finally, if nothing works, try cleaning the apt archive lock using the following command.
sudo rm -f /var/cache/apt/archives/lock
So, that’s all.
Wrapping Up
In this article, I have explained various ways to resolve this typical error in Ubuntu Linux and related distributions. I am sure any one of the methods should work for you.
Do let me know in the comment box which command worked out for you for the benefit of others.
При использовании утилиты apt для установки или обновления программного обеспечения в таких дистрибутивах как Ubuntu и Debian, в терминале можно столкнуться со следующей ошибкой: Unable to lock directory /var/lib/apt/lists.
Данная ошибка очень проста и исправить её не составит труда, но для новых пользователей она может показаться серьезным препятствием. В этой статье будет рассмотрено что означает ошибка Unable to lock directory /var/lib/apt/lists, а также как устранить эту проблему.
Что значит эта ошибка
В операционной системе Ubuntu 20.04 получить данную ошибку можно при выполнении таких команд как apt update, apt upgrade или apt install. А полный текст ошибки выглядит вот так:
- E: Could not get lock /var/lib/apt/lists/lock. It is held by process 4746 (aptd)
- N: Be aware that removing the lock file is not a solution and may break your system.
- E: Unable to lock directory /var/lib/apt/lists/
Так же можно получить следующую ошибку:
Waiting for cache lock: Coud not get lock /var/lib/dpkg/lock-frontend. It is held by process
Если дословно перевести значение данной ошибки, то утилита сообщает что не может создать файл блокировки /var/lib/apt/lists/lock далее утилита спрашивает нет ли уже запущенного второго экземпляра программы apt, который уже создал этот файл и сейчас работает с данной директорией.
Как правило данная ошибка появляется из-за того, что уже запущен другой экземпляр программы apt который или обновляет пакеты операционной системы или устанавливает какие-либо программы. Когда команда apt или графическое приложение для обновления системы обновляют систему или устанавливают новое программное обеспечение, они блокируют файл dpkg (менеджер пакетов в операционных системах семейства Debian).
Эта блокировка выполняется для того, чтобы два процесса не изменяли содержимое файла dpkg одновременно, так как это может привести к неоправданному риску поломки всей системы.
Также данная ошибка может возникать при выполнении автоматических обновлений. За данную опцию отвечает пакет под именем unattended-upgrades который как правило присутствует в большинстве дистрибутивов по умолчанию и запускается автоматически при загрузке операционной системы.
Существует несколько способов решения данной проблемы. Рассмотрим все возможные варианты. Первый способ этой найти запущенный процесс apt и завершить его. Для этого сначала необходимо выполнить команду в терминале:
ps aux | grep -i apt
Данная команда отобразит идентификатор процесса, выполняющего процесс apt. В приведенном выше примере идентификатор процесса — 28382.
Можно использовать идентификатор процесса, чтобы завершить его. Необходимо заменить идентификатор процесса числом, которое было получено в выводе предыдущей команды. В данном примере это число 28382. Команда будет выглядеть следующем образом:
sudo kill 28382
Далее необходимо проверить, был ли процесс остановлен, запустив команду ps aux | grep -i apt еще раз. Если процесс все еще работает, его необходимо принудительно уничтожить при помощи команды:
sudo kill -9 28382
Другой, более простой способ — использовать команду killall, она завершит все экземпляры запущенной программы. Для этого необходимо выполнить команду:
sudo killall apt apt-get
Второй способ заключается в удаление файлов блокировки. Но, прежде чем удалять данные файлы, необходимо остановить процессы, использующие файлы блокировки. Для этого необходимо выполнить одну из следующих команд ориентируясь на ту, которая вернет число:
sudo lsof /var/lib/dpkg/lock
sudo lsof /var/lib/apt/lists/lock
sudo lsof /var/cache/apt/archives/lock
Возможно, команды ничего не будут возвращать или вернут только одно число. Полученное число из вывода необходимо использовать чтобы завершить процесс (необходимо заменить process_id числом, полученным из приведенных выше команд):
sudo kill -9 process_id
И только после этого можно безопасно удалить файлы блокировки, используя следующие команды:
sudo rm /var/lib/apt/lists/lock
sudo rm /var/cache/apt/archives/lock
sudo rm /var/lib/dpkg/lock
После удаления файлов блокировки необходимо переконфигурировать пакеты при помощи команды:
sudo dpkg --configure -a
Выводы
В данной статье были рассмотрены два способа решения ошибки Unable to lock directory /var/lib/apt/lists которая может вызвать затруднения у новых пользователей. Но теперь вы знаете почему она появляется и как с ней бороться. Если у вас остались вопросы, пишите в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .