Содержание
- Как исправить ошибку «E: Could not get lock /var/lib/dpkg/lock» в Ubuntu Linux
- Как исправить ошибку «Unable to lock the administration directory (/var/lib/dpkg/)»
- Метод 0:
- Метод 1:
- Метод 2:
- Устранение неполадки: «Unable to acquire the dpkg frontend lock»
- Устранение неполадки: «dpkg: error: dpkg frontend is locked by another process»
- Помогла ли вам статья? Какой из методов помог в вашем случае?
- How to Fix ‘E: Could not get lock /var/lib/dpkg/lock’ Error in Ubuntu Linux
- Fixing “Unable to lock the administration directory (/var/lib/dpkg/)” error
- Method 0:
- Method 1:
- Method 2
- Troubleshooting 1: “Unable to acquire the dpkg frontend lock”
- Troubleshooting 2: “dpkg: error: dpkg frontend is locked by another process”
Как исправить ошибку «E: Could not get lock /var/lib/dpkg/lock» в Ubuntu Linux
Недавно, устанавливая приложение с помощью команды apt в Ubuntu, я столкнулся со следующей ошибкой:
Если вы столкнётесь с какой-то из перечисленных ниже ошибок, знайте, фактически у вас та же ошибка, что и у меня:
В некоторых случаях подобные ошибки возникают при использовании Центра программного обеспечения.
И в целом, они напоминают еще одну распространенную ошибку:
Unable to lock directory/var/cache/apt/archives/ и, как говорится «подобное лечится подобно», а похожие ошибки и фиксятся похоже.
Как исправить ошибку «Unable to lock the administration directory (/var/lib/dpkg/)»
Вы видите эту ошибку, потому что какая-то другая программа обновляет Ubuntu прямо сейчас. Когда команда или приложение обновляют систему или устанавливают новое программное обеспечение, они блокируют файл dpkg (менеджер пакетов Debian).
Эта блокировка выполняется для того, чтобы два процесса не изменяли содержимое файла dpkgодновременно, так как это может привести к неоправданному риску поломки всей системы.
Давайте посмотрим, что мы можем сделать, чтобы решить проблему «unable to lock the administrator directory».
Метод 0:
Первое, что следует сделать, это проверить, может ли какая-то другая программа запускать обновление системы или устанавливать программу.
Если вы используете командную строку, проверьте, не запускает ли одно из следующих приложений: Software Center, Software Updater, менеджер пакетов Synaptic или Gdebi, какое-нибудь обновление / установку. В случае положительного ответа – просто подождите, пока программа завершит выполнение.
Если ни одно из этих приложений не запущено, проверьте все открытые окна терминала и посмотрите, не запустили ли вы самостоятельно какие-либо обновление или установки. Если да, дождитесь завершения этих процессов. (Совет странный, но помните, что все мы бываем невнимательны))
Если ничего из вышеперечисленного не происходит, проверьте, какой еще процесс выполняет команду apt (менеджер пакетов для работы с программным обеспечением). Используйте эту команду:
В моем случае команда вернула такой результат:
Если вы, как и я, видите, что apt используется такой программой, как apt.systemd.daily update, вам повезло, мой дорогой читатель.
Это «демон», который работает в фоновом режиме и автоматически проверяет наличие обновлений системы при запуске системы.
В Ubuntu 18.04 и более поздних версиях он может даже попытаться загрузить и установить важные обновления безопасности самостоятельно. По крайней мере, такие опции я увидел в дефолтных настройках в инструменте «Программное обеспечение и обновления» на рабочем столе Ubuntu.
Если вы находитесь на сервере Ubuntu, вы можете проверить, включены ли у вас автоматические обновления, проверив содержимое файла /etc/apt/apt.conf.d/20auto-upgrades.
Итак, если вы выяснили, что apt.systemd.daily использует процесс apt, все, что вам нужно сделать, это подождать несколько минут. Когда автоматическое обновление завершится, вы сможете установить свое программное обеспечение как обычно.
В качестве постоянного решения вы можете полностью отключить как автоматическую проверку наличия обновлений, так и сами автообновления, однако я бы не советовал, из соображений безопасности.
Это был самый простой и легко побеждаемый сценарий. К сожалению, он не единственный возможный. Если apt использует какая-то другая программа, то и решение будет другим.
Метод 1:
Используйте командную строку Linux, чтобы найти и остановить запущенный процесс. Для этого используйте команду ниже:
Эта команда покажет вам идентификатор процесса, выполняющего apt или apt-get. В приведенном ниже примере идентификатор процесса — 7343. Не обращайте внимания на последнюю строку, содержащую «grep –color = auto».
Вы можете использовать идентификатор процесса, чтобы завершить его, отправив команду SIGTERM. Замените
числом, которое вы получили в выводе предыдущей команды.
Проверьте, был ли процесс остановлен, запустив команду «ps aux | grep -i apt» еще раз. Если он все еще работает, принудительно уничтожьте его сигналом SIGKILL:
Другой, более простой способ — использовать команду killall, она убьет все экземпляры запущенной программы:
Метод 2:
Вышеупомянутый метод решит проблему в большинстве случаев. Но мой случай, по закону подлости, был немного другим. Я обновлял свою систему и случайно закрыл терминал. По этой причине не было процессов, использующих apt, но система все равно выдавала мне ошибку.
В таком случае основной причиной является файл блокировки. Как упоминалось ранее, файлы блокировки необходимы для предотвращения использования одних и тех же данных двумя или более процессами. Когда выполняются команды apt или apt-get, они создают файлы блокировки в нескольких местах. Если предыдущая команда apt не была завершена должным образом, файлы блокировки не удаляются и, следовательно, они будут блокировать любые новые вызовы команд apt-get или apt.
Чтобы решить эту проблему, все, что вам нужно сделать, это удалить файлы блокировки. Но, прежде чем вы это сделаете, было бы неплохо остановить любой процесс, использующий файлы блокировки.
Используйте команду lsof, чтобы получить идентификатор процесса, использующего файлы блокировки. Проверьте ошибку и посмотрите, на какие файлы блокировки она жалуется, и получите идентификатор процессов, содержащих эти файлы блокировки.
Последовательно запустите эти команды:
Возможно, команды ничего не будут возвращают или вернут только одно число. Но, если они возвращают хотя бы одно число, используйте его, чтобы завершить такие процессы (замените
числами, полученными из приведенных выше команд):
Теперь вы можете безопасно удалить файлы блокировки, используя следующие команды:
После этого переконфигурируйте пакеты:
Теперь, если вы запустите команду sudo apt update, все должно работать как надо.
Устранение неполадки: «Unable to acquire the dpkg frontend lock»
Если вы видите такую ошибку:
Вы должны выяснить, какой процесс удерживает интерфейс блокировки, используя команду lsof, как обсуждалось в предыдущих разделах:
В моем случае команда вернула:
Если вы видите значение «unattende» в столбце COMMAND, это значит, что выполняются автоматические обновления безопасности. Вам следует дождаться завершения процессов. По сути, это то, что я описывал в методе 0, но вы могли его пропустить.
Если значение COMMAND какое-то другое, вы можете убить процесс, а затем удалить файл блокировки. Идентификатор процесса вы найдете в столбце PID. Используйте этот PID, чтобы убить процесс. После этого удалите файл блокировки и запустите команду обновления, чтобы проверить, исправили ли вы проблему.
Устранение неполадки: «dpkg: error: dpkg frontend is locked by another process»
Если вы встретите ошибку «интерфейс dpkg заблокирован другим процессом» в процессе пошагового выполнения метода 2, вам понадобится выполнить еще одно действие.
Во-первых, узнайте идентификатор процесса, хранящего файл блокировки.
Эта команда предоставит вам подробную информацию о процессах и программах, использующих файлы блокировки. Используйте идентификатор процесса, чтобы убить эту программу:
Теперь вы можете снять блокировку и перенастроить dpkg:
Помогла ли вам статья? Какой из методов помог в вашем случае?
Надеюсь, этот небольшой пост помог вам исправить ошибки типа «Не удалось получить lock / var / lib / dpkg / lock». Если да – обязательно поделитесь в комментах, какой метод помог именно вам.
Если ни один из перечисленных способов так и не помог вам справиться с проблемой, опять же – дайте знать. Я постараюсь вам помочь.
Любые другие предложения также приветствуются в комментариях.
Источник
How to Fix ‘E: Could not get lock /var/lib/dpkg/lock’ Error in Ubuntu Linux
Recently I was trying to install an application using the apt command on Ubuntu when I encountered the following error:
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?
In fact, there is a similar error you may see:
E: Could not get lock /var/lib/apt/lists/lock – open (11: Resource temporarily unavailable)
E: Unable to lock directory /var/lib/apt/lists/
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?
In some cases, you might see it while using the Software Center:

These errors are very similar to another common Ubuntu error, Unable to lock directory /var/cache/apt/archives/, and the interesting thing is that the fixes are similar as well.
Fixing “Unable to lock the administration directory (/var/lib/dpkg/)” error
You see this error because some other program is trying to update Ubuntu. When a command or application is updating the system or installing a new software, it locks the dpkg file (Debian package manager).
This locking is done so that two processes don’t change the content at the same time as it may lead to unwarranted situation and a possible broken system.
Let’s see what steps can you take to fix this issue of ‘unable to lock administration directory’.
Method 0:
The first thing you should do is to check if some other program could be running system update or installing a program.
If you are using command line, check if an application like Software Center, Software Updater, Synaptic package manager, Gdebi is running any update/installation. If that’s the case, please wait for the program to finish the running process.
If there is no such application running, please check all the open terminal windows and see if you are running an update or installing a program. If yes, wait for it to finish.
If none of the above is happening, check which other process is running the apt command (package manager for handling software). Use this command:
For me, it showed this output:
If you see that apt is being used by a program like apt.systemd.daily update, you are in luck, my dear reader.
This is a daemon that runs in the background and check for system updates automatically when you start your system.
In Ubuntu 18.04 and higher versions, it may even try to download and install the important security updates on its own. At least this is what I see in the default settings in Software & Updates tool on the Ubuntu desktop.

If you are on Ubuntu server, you may check whether you have unattended upgrades enabled by checking the content of the file /etc/apt/apt.conf.d/20auto-upgrades.
So if you see apt.systemd.daily is using the apt process, all you have to do is to wait for a few minutes. When the automatic update finishes, you should be able to install your software as usual.
As a permanent solution, you may disable the check for automatic update and unattended upgrades altogether however I won’t advise that for security reasons.
Now, that was the simple scenario and it could be handled easily. But that might not always be the case. If some other program is using apt, you need to handle it differently.
Method 1:
Use the Linux command line to find and kill the running process. To do that, use the command below:
This will show you the id of the process running apt or apt-get. In the example below, the process id is 7343. You can ignore the last line containing ‘grep –color=auto’.
You can use the process id to terminate it by sending the SIGTERM signal. Replace the
with the number you got in the output of previous command.
Check if the process was killed by running the ‘ps aux | grep -i apt’ command. If it is still running, force kill it with SIGKILL signal:
Another easier way would be to use the killall command. This will kill all the instances of a running program:
Method 2
The above method would fix the problem for you in most cases. But my case was a bit different. I was updating my system and accidentally closed the terminal. For that reason, there were no processes running apt, but it still showed me the error.
In this case, the root cause is the lock file. As mentioned earlier, the lock files are used to prevent two or more processes from using the same data. When apt or apt-get commands are run, they create lock files in a few places. If the previous apt command was not terminated properly, the lock files are not deleted and hence they prevent any new instances of apt-get or apt commands.
To fix the problem, all you need to do is to remove the lock files. But before you do that, it would be a good idea to stop any process that is using the lock files.
Use the lsof command to get the process ID of the process holding the lock files. Check the error and see what lock files it is complaining about and get the id of the processes holding these lock files.
Run these commands one by one.
It’s possible that the commands don’t return anything, or return just one number. If they do return at least one number, use the number(s) and kill the processes like this (replace the
with the numbers you got from the above commands):
You can now safely remove the lock files using the commands below:
After that, reconfigure the packages:
Now if you run the sudo apt update command, everything should be fine.
Troubleshooting 1: “Unable to acquire the dpkg frontend lock”
If you see an error like this:
You should find out which process is holding the lock-frontend using the lsof command as discussed in previous sections:
This is what it showed for me:
If you see ‘unattende‘ COMMAND column, this means unattended security upgrades are running. You should wait for the process to finish. Basically, this is what I discussed in method 0 but you probably skipped that.
If the COMMAND is something else, you may kill the process and then remove the lock file. You can see the process id under the PID column. Use this PID to kill the process. After that, remove the lock file and run the update command to see if it’s been fixed.
What’s that lsof: warning can’t stat() fuse.gvfsd-fuse file system?
Note: If you see “lsof: warning can’t stat() fuse.gvfsd-fuse file system /run/user/1000/gvfs
Output information may be incomplete” lines after running the earlier mentioned lsof command, don’t panic.
That’s not an error. It’s just that lsof tries to look into mounted file systems as well and the warning is about those mounted systems.
The files are locked by the processes on your main filesystem so if it shows some warning and no output, this only means that there is no process using those lock files.
Troubleshooting 2: “dpkg: error: dpkg frontend is locked by another process”
If you see the error “dpkg frontend is locked by another process” while running the steps in method 2, you need to one additional step.
First, find out the id of the process that is holding the lock file.
The above command will give you the details of the processes using the lock files. Use the process ID to kill this program:
Now you can remove the lock and reconfigure dpkg:
Did it work for you? Which method fixed it for you?

I hope this small tip helped you fix the “Could not get lock /var/lib/dpkg/lock” error. If yes, please let me know which method worked for you in the comments.
If you are still facing issues, let me know. I’ll try to help you out.
Any other suggestions are also welcome in the comments.
Источник
In this article we are going to learn ‘Fix dpkg: error: dpkg frontend lock is locked by another process’. Whenever we are installing software, an error occurs with ‘dpkg: error: dpkg frontend lock is locked by another process’. dpkg is a free operating system software at the bottom of the package management system in Debian and its numerous derivatives. dpkg is used to install, remove, and supply information about .deb packages.
The dpkg (Debian package) itself is a low-level tool. APT (Advanced Package Tool), a high-level tool, is more commonly used than dpkg because it can bring packages to remote locations and deal with complex package relationships such as dependency fixes. Frontends like Aptitude (NCRS) and Synaptic (GTK +) are used for their friendly interface for APT.
The Debian package “dpkg” provides the dpkg program, as well as many other programs required for the run-time operation of the packaging system, including DPKG-DEB, DPKG-Split, DPKG-Query, DPKG-Statoveride, DPKG-Diverse, and DPKG. Trigger.
This includes programs like Update-Option and Start-Stop-Demon. The install-info was used to include the program as well but was later removed because it has now been developed and distributed separately. The Debian package “DPKG-Dev” contains the numerous build tools described below.
Follow the below steps to Fix DPKG: Error: DPKG Frontend Lock is Locked By Another Process
If you find the “dpkg: error: dpkg frontend lock is locked by another process” error while running the procedure described above, you need to do an extra step. First, find the ID of the process that contains the lock file. You can do so using below command.
[email protected]:~$ lsof /var/lib/dpkg/lock
Then make sure the process is not running.
[email protected]:~$ ps cax | grep PID PID TTY STAT TIME COMMAND
The above command will give you the process PID using lock files. Use this PID to kill the process.
[email protected]:~$ kill PID bash: kill: PID: arguments must be process or job IDs [email protected]:~$ kill -9 PID bash: kill: PID: arguments must be process or job IDs
Also Read – A Guide to Kill, Pkill and Killall Commands to Stop the Process in Linux(Kill Process Linux)
That’s all, In this article, we have explained the Fix dpkg: error: dpkg frontend lock is locked by another process. I hope you enjoy this article. If you like this article, then just share it. If you have any questions about this article, please comment.
ITSmarttricks Team
This is Mangesh Dhulap the Founder and Editor of IT SMART TRICKS have 6+ years of Industrial Experience. We expect from our visitors to like, share, and comment on our posts.
Recently I was trying to install an application using the apt command on Ubuntu when I encountered the following error:
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?
In fact, there is a similar error you may see:
E: Could not get lock /var/lib/apt/lists/lock – open (11: Resource temporarily unavailable)
E: Unable to lock directory /var/lib/apt/lists/
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?
In some cases, you might see it while using the Software Center:
These errors are very similar to another common Ubuntu error, Unable to lock directory /var/cache/apt/archives/, and the interesting thing is that the fixes are similar as well.
Fixing “Unable to lock the administration directory (/var/lib/dpkg/)” error
You see this error because some other program is trying to update Ubuntu. When a command or application is updating the system or installing a new software, it locks the dpkg file (Debian package manager).
This locking is done so that two processes don’t change the content at the same time as it may lead to unwarranted situation and a possible broken system.
Let’s see what steps can you take to fix this issue of ‘unable to lock administration directory’.
Method 0:
The first thing you should do is to check if some other program could be running system update or installing a program.
If you are using command line, check if an application like Software Center, Software Updater, Synaptic package manager, Gdebi is running any update/installation. If that’s the case, please wait for the program to finish the running process.
If there is no such application running, please check all the open terminal windows and see if you are running an update or installing a program. If yes, wait for it to finish.
If none of the above is happening, check which other process is running the apt command (package manager for handling software). Use this command:
ps aux | grep -i apt
For me, it showed this output:
[email protected]:~$ ps aux | grep -i apt
root 1464 0.0 0.0 4624 772 ? Ss 19:08 0:00 /bin/sh /usr/lib/apt/apt.systemd.daily update
root 1484 0.0 0.0 4624 1676 ? S 19:08 0:00 /bin/sh /usr/lib/apt/apt.systemd.daily lock_is_held update
_apt 2836 0.8 0.1 96912 9432 ? S 19:09 0:03 /usr/lib/apt/methods/http
abhishek 6172 0.0 0.0 21532 1152 pts/1 S+ 19:16 0:00 grep --color=auto -i apt
If you see that apt is being used by a program like apt.systemd.daily update, you are in luck, my dear reader.
This is a daemon that runs in the background and check for system updates automatically when you start your system.
In Ubuntu 18.04 and higher versions, it may even try to download and install the important security updates on its own. At least this is what I see in the default settings in Software & Updates tool on the Ubuntu desktop.
If you are on Ubuntu server, you may check whether you have unattended upgrades enabled by checking the content of the file /etc/apt/apt.conf.d/20auto-upgrades.
So if you see apt.systemd.daily is using the apt process, all you have to do is to wait for a few minutes. When the automatic update finishes, you should be able to install your software as usual.
As a permanent solution, you may disable the check for automatic update and unattended upgrades altogether however I won’t advise that for security reasons.
Now, that was the simple scenario and it could be handled easily. But that might not always be the case. If some other program is using apt, you need to handle it differently.
Method 1:
Use the Linux command line to find and kill the running process. To do that, use the command below:
ps aux | grep -i apt
This will show you the id of the process running apt or apt-get. In the example below, the process id is 7343. You can ignore the last line containing ‘grep –color=auto’.
You can use the process id to terminate it by sending the SIGTERM signal. Replace the <process_id> with the number you got in the output of previous command.
sudo kill <process_id>
Check if the process was killed by running the ‘ps aux | grep -i apt’ command. If it is still running, force kill it with SIGKILL signal:
sudo kill -9 <process_id>
Another easier way would be to use the killall command. This will kill all the instances of a running program:
sudo killall apt apt-get
Method 2
The above method would fix the problem for you in most cases. But my case was a bit different. I was updating my system and accidentally closed the terminal. For that reason, there were no processes running apt, but it still showed me the error.
🚧
I would advise trying the above two methods or simply restarting your system first. If none of that works, then only you go for this option of removing the lock files.
In this case, the root cause is the lock file. As mentioned earlier, the lock files are used to prevent two or more processes from using the same data. When apt or apt-get commands are run, they create lock files in a few places. If the previous apt command was not terminated properly, the lock files are not deleted and hence they prevent any new instances of apt-get or apt commands.
To fix the problem, all you need to do is to remove the lock files. But before you do that, it would be a good idea to stop any process that is using the lock files.
Use the lsof command to get the process ID of the process holding the lock files. Check the error and see what lock files it is complaining about and get the id of the processes holding these lock files.
Run these commands one by one.
sudo lsof /var/lib/dpkg/lock
sudo lsof /var/lib/apt/lists/lock
sudo lsof /var/cache/apt/archives/lock
It’s possible that the commands don’t return anything, or return just one number. If they do return at least one number, use the number(s) and kill the processes like this (replace the <process_id> with the numbers you got from the above commands):
sudo kill -9 <process_id>
You can now safely remove the lock files using the commands below:
sudo rm /var/lib/apt/lists/lock
sudo rm /var/cache/apt/archives/lock
sudo rm /var/lib/dpkg/lock
After that, reconfigure the packages:
sudo dpkg --configure -a
Now if you run the sudo apt update command, everything should be fine.
Troubleshooting 1: “Unable to acquire the dpkg frontend lock”
If you see an error like this:
[email protected]:~$ sudo apt install grub-customizer
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
You should find out which process is holding the lock-frontend using the lsof command as discussed in previous sections:
sudo lsof /var/lib/dpkg/lock-frontend
This is what it showed for me:
[email protected]:~$ sudo lsof /var/lib/dpkg/lock-frontend
lsof: WARNING: can't stat() fuse.gvfsd-fuse file system /run/user/1000/gvfs
Output information may be incomplete.
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
unattende 2823 root 5uW REG 8,2 0 145221 /var/lib/dpkg/lock-frontend
If you see ‘unattende‘ COMMAND column, this means unattended security upgrades are running. You should wait for the process to finish. Basically, this is what I discussed in method 0 but you probably skipped that.
If the COMMAND is something else, you may kill the process and then remove the lock file. You can see the process id under the PID column. Use this PID to kill the process. After that, remove the lock file and run the update command to see if it’s been fixed.
sudo kill -9 PID
sudo rm /var/lib/dpkg/lock-frontend
sudo apt update
What’s that lsof: warning can’t stat() fuse.gvfsd-fuse file system?
Note: If you see “lsof: warning can’t stat() fuse.gvfsd-fuse file system /run/user/1000/gvfs
Output information may be incomplete” lines after running the earlier mentioned lsof command, don’t panic.
That’s not an error. It’s just that lsof tries to look into mounted file systems as well and the warning is about those mounted systems.
The files are locked by the processes on your main filesystem so if it shows some warning and no output, this only means that there is no process using those lock files.
Troubleshooting 2: “dpkg: error: dpkg frontend is locked by another process”
If you see the error “dpkg frontend is locked by another process” while running the steps in method 2, you need to one additional step.
First, find out the id of the process that is holding the lock file.
sudo lsof /var/lib/dpkg/lock-frontend
The above command will give you the details of the processes using the lock files. Use the process ID to kill this program:
sudo kill -9 PID
Now you can remove the lock and reconfigure dpkg:
sudo rm /var/lib/dpkg/lock-frontend
sudo dpkg --configure -a
Did it work for you? Which method fixed it for you?
I hope this small tip helped you fix the “Could not get lock /var/lib/dpkg/lock” error. If yes, please let me know which method worked for you in the comments.
If you are still facing issues, let me know. I’ll try to help you out.
Any other suggestions are also welcome in the comments.
Недавно, устанавливая приложение с помощью команды apt в Ubuntu, я столкнулся со следующей ошибкой:
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?
Если вы столкнётесь с какой-то из перечисленных ниже ошибок, знайте, фактически у вас та же ошибка, что и у меня:
E: Could not get lock /var/lib/apt/lists/lock – open (11: Resource temporarily unavailable) E: Unable to lock directory /var/lib/apt/lists/ 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?
В некоторых случаях подобные ошибки возникают при использовании Центра программного обеспечения.
И в целом, они напоминают еще одну распространенную ошибку:
Unable to lock directory/var/cache/apt/archives/ и, как говорится «подобное лечится подобно», а похожие ошибки и фиксятся похоже.
Как исправить ошибку «Unable to lock the administration directory (/var/lib/dpkg/)»
Вы видите эту ошибку, потому что какая-то другая программа обновляет Ubuntu прямо сейчас. Когда команда или приложение обновляют систему или устанавливают новое программное обеспечение, они блокируют файл dpkg (менеджер пакетов Debian).
Эта блокировка выполняется для того, чтобы два процесса не изменяли содержимое файла dpkgодновременно, так как это может привести к неоправданному риску поломки всей системы.
Давайте посмотрим, что мы можем сделать, чтобы решить проблему «unable to lock the administrator directory».
Метод 0:
Первое, что следует сделать, это проверить, может ли какая-то другая программа запускать обновление системы или устанавливать программу.
Если вы используете командную строку, проверьте, не запускает ли одно из следующих приложений: Software Center, Software Updater, менеджер пакетов Synaptic или Gdebi, какое-нибудь обновление / установку. В случае положительного ответа – просто подождите, пока программа завершит выполнение.
Если ни одно из этих приложений не запущено, проверьте все открытые окна терминала и посмотрите, не запустили ли вы самостоятельно какие-либо обновление или установки. Если да, дождитесь завершения этих процессов. (Совет странный, но помните, что все мы бываем невнимательны))
Если ничего из вышеперечисленного не происходит, проверьте, какой еще процесс выполняет команду apt (менеджер пакетов для работы с программным обеспечением). Используйте эту команду:
ps aux | grep -i apt
В моем случае команда вернула такой результат:
abhishek@nuc:~$ ps aux | grep -i apt root 1464 0.0 0.0 4624 772 ? Ss 19:08 0:00 /bin/sh /usr/lib/apt/apt.systemd.daily update root 1484 0.0 0.0 4624 1676 ? S 19:08 0:00 /bin/sh /usr/lib/apt/apt.systemd.daily lock_is_held update _apt 2836 0.8 0.1 96912 9432 ? S 19:09 0:03 /usr/lib/apt/methods/http abhishek 6172 0.0 0.0 21532 1152 pts/1 S+ 19:16 0:00 grep --color=auto -i apt
Если вы, как и я, видите, что apt используется такой программой, как apt.systemd.daily update, вам повезло, мой дорогой читатель.
Это «демон», который работает в фоновом режиме и автоматически проверяет наличие обновлений системы при запуске системы.
В Ubuntu 18.04 и более поздних версиях он может даже попытаться загрузить и установить важные обновления безопасности самостоятельно. По крайней мере, такие опции я увидел в дефолтных настройках в инструменте «Программное обеспечение и обновления» на рабочем столе Ubuntu.
Если вы находитесь на сервере Ubuntu, вы можете проверить, включены ли у вас автоматические обновления, проверив содержимое файла /etc/apt/apt.conf.d/20auto-upgrades.
Итак, если вы выяснили, что apt.systemd.daily использует процесс apt, все, что вам нужно сделать, это подождать несколько минут. Когда автоматическое обновление завершится, вы сможете установить свое программное обеспечение как обычно.
В качестве постоянного решения вы можете полностью отключить как автоматическую проверку наличия обновлений, так и сами автообновления, однако я бы не советовал, из соображений безопасности.
Это был самый простой и легко побеждаемый сценарий. К сожалению, он не единственный возможный. Если apt использует какая-то другая программа, то и решение будет другим.
Метод 1:
Используйте командную строку Linux, чтобы найти и остановить запущенный процесс. Для этого используйте команду ниже:
ps aux | grep -i apt
Эта команда покажет вам идентификатор процесса, выполняющего apt или apt-get. В приведенном ниже примере идентификатор процесса — 7343. Не обращайте внимания на последнюю строку, содержащую «grep –color = auto».
Вы можете использовать идентификатор процесса, чтобы завершить его, отправив команду SIGTERM. Замените <process_id> числом, которое вы получили в выводе предыдущей команды.
sudo kill < process_id >
Проверьте, был ли процесс остановлен, запустив команду «ps aux | grep -i apt» еще раз. Если он все еще работает, принудительно уничтожьте его сигналом SIGKILL:
sudo kill -9 < process_id >
Другой, более простой способ — использовать команду killall, она убьет все экземпляры запущенной программы:
sudo killall apt apt-get
Метод 2:
Вышеупомянутый метод решит проблему в большинстве случаев. Но мой случай, по закону подлости, был немного другим. Я обновлял свою систему и случайно закрыл терминал. По этой причине не было процессов, использующих apt, но система все равно выдавала мне ошибку.
В таком случае основной причиной является файл блокировки. Как упоминалось ранее, файлы блокировки необходимы для предотвращения использования одних и тех же данных двумя или более процессами. Когда выполняются команды apt или apt-get, они создают файлы блокировки в нескольких местах. Если предыдущая команда apt не была завершена должным образом, файлы блокировки не удаляются и, следовательно, они будут блокировать любые новые вызовы команд apt-get или apt.
Чтобы решить эту проблему, все, что вам нужно сделать, это удалить файлы блокировки. Но, прежде чем вы это сделаете, было бы неплохо остановить любой процесс, использующий файлы блокировки.
Используйте команду lsof, чтобы получить идентификатор процесса, использующего файлы блокировки. Проверьте ошибку и посмотрите, на какие файлы блокировки она жалуется, и получите идентификатор процессов, содержащих эти файлы блокировки.
Последовательно запустите эти команды:
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
Теперь, если вы запустите команду sudo apt update, все должно работать как надо.
Устранение неполадки: «Unable to acquire the dpkg frontend lock»
Если вы видите такую ошибку:
abhishek@nuc:~$ sudo apt install grub-customizer E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable) E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
Вы должны выяснить, какой процесс удерживает интерфейс блокировки, используя команду lsof, как обсуждалось в предыдущих разделах:
sudo lsof /var/lib/dpkg/lock-frontend
В моем случае команда вернула:
abhishek@nuc:~$ sudo lsof /var/lib/dpkg/lock-frontend
lsof: WARNING: can't stat() fuse.gvfsd-fuse file system
/run/user/1000/gvfs
Output information may be incomplete.
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
unattende 2823 root 5uW REG 8,2 0 145221
/var/lib/dpkg/lock-frontend
Если вы видите значение «unattende» в столбце COMMAND, это значит, что выполняются автоматические обновления безопасности. Вам следует дождаться завершения процессов. По сути, это то, что я описывал в методе 0, но вы могли его пропустить.
Если значение COMMAND какое-то другое, вы можете убить процесс, а затем удалить файл блокировки. Идентификатор процесса вы найдете в столбце PID. Используйте этот PID, чтобы убить процесс. После этого удалите файл блокировки и запустите команду обновления, чтобы проверить, исправили ли вы проблему.
sudo kill -9 PID sudo rm /var/lib/dpkg/lock-frontend sudo apt update
Устранение неполадки: «dpkg: error: dpkg frontend is locked by another process»
Если вы встретите ошибку «интерфейс dpkg заблокирован другим процессом» в процессе пошагового выполнения метода 2, вам понадобится выполнить еще одно действие.
Во-первых, узнайте идентификатор процесса, хранящего файл блокировки.
sudo lsof /var/lib/dpkg/lock-frontend
Эта команда предоставит вам подробную информацию о процессах и программах, использующих файлы блокировки. Используйте идентификатор процесса, чтобы убить эту программу:
sudo kill -9 PID
Теперь вы можете снять блокировку и перенастроить dpkg:
sudo rm /var/lib/dpkg/lock-frontend sudo dpkg --configure -a
Помогла ли вам статья? Какой из методов помог в вашем случае?
Надеюсь, этот небольшой пост помог вам исправить ошибки типа «Не удалось получить lock / var / lib / dpkg / lock». Если да – обязательно поделитесь в комментах, какой метод помог именно вам.
Если ни один из перечисленных способов так и не помог вам справиться с проблемой, опять же – дайте знать. Я постараюсь вам помочь.
Любые другие предложения также приветствуются в комментариях.
Unable to acquire the dpkg frontend lock error is the most common error that happens with Linux systems, this can be solved easily. This error is being displayed because another programme is attempting to update Ubuntu. A command or application locks the dpkg file when upgrading the system or installing new software (Debian package manager).
The error “unable to acquire the dpkg frontend lock” happened due to various reasons and can be solved by understanding the cause of the problem.
We can run the following command to check the error log and take a look at the process ID and error message.
$ sudo lsof /var/lib/dpkg/lock-frontend
frontend-lock-log
So here are a few common causes and their fixes:-
1. Unprivileged access
sudo-error
$ apt install nano E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied) E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
In this case, the user doesn’t have access to run the particular command without having root access so users must use sudo to run the command before running it.
2. Broken package
dpkg: error: his package provides frequent translation updates.': version string has embedded spaces E: Sub-process /usr/bin/dpkg returned an error code (2)
sometimes when we try to install the app, the app can be broken due to connection loss and various other reasons, in this case, we can run the following command to fix this:-
$ sudo dpkg --configure -a or $ sudo apt install -f
3. Installing an app from unlisted repositories or missing repositories
add=ppa
$ sudo apt install grub-customizer E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable) E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
installed
Due to a typo or unavailability of apps in the repository it happens, in this case, you have to check the app ppa repository and add to the package repository, see in this thread for more details.
4. Frontend is locked by another process
Check if any process is running and using apt/dpkg
$ ps aux | grep -i apt
this is a dpkg error and finding the process id using the log command and by killing that PID will fix the issue
$ sudo kill -9 <PID> or $ sudo killall program_name
kill-example
5. Delete the lock file to fix the issue
This is a brute force method and you should use it carefully, although this also fixes the issue but system can be broken if you use this without understanding the error. Often restarting system can also fix the error so you must try restart before trying this step.
$ sudo rm /var/lib/apt/lists/lock $ sudo rm /var/cache/apt/archives/lock $ sudo rm /var/lib/dpkg/lock
delete-lock-file
I hope this article is helpful, give a like, happy learning.
Introduction
In Ubuntu, you may sometimes encounter an error when attempting to run an apt command:
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?
This message lets you know that dpkg, the Debian Package Manager service, is unavailable.
Use the options in this guide to resolve the Ubuntu «Could not get lock…» error.

Prerequisites
- Access to a terminal window / command line
- A user account with sudo or root privileges
By default, the update service launches when Ubuntu starts. The automatic updater uses dpkg to check and install updates.
The dpkg service locks itself so that two processes don’t update the content simultaneously. The service is locked to avoid potential corruptions in the system. However, it also means that the user cannot, for example, run a simple apt command.
1: Wait it Out or Reboot
Give the system up to 10 minutes after you see the error, then try your software installation again.
If you’re certain that nothing is being installed, you can reboot the machine and try again.
To adjust the settings for automatic updates:
1. Click Activites > Search.
2. Type Updates.
3. Click the icon for Software & Updates.
4. Use the check boxes and drop-down menus to select your preferred update schedule.

Note: We recommend keeping automatic updates turned on. Optionally, you can set them to be less frequent or to notify you instead of automatic downloading.
2: Examine the Running Processes
1. If you already tried waiting and rebooting the system, and you still get the error, use the following command to see which installation services are running:
ps aux | grep -i apt
2. If there are any applications using apt, they will appear on the list. Look for an entry similar to:
/usr/lib/apt/apt.systemd.daily update

3. The daily update message means your system is running normal updates. You have to wait for this process to finish, but no other action is required.
You may have another apt process that’s running:
root 2810 0.0 0.0 72948 4312 pts/0 S+ 15:03 0:00 sudo apt-get remove logstash
The most important columns are the second column, which lists the PID (process ID), and the last column that displays the service that’s using apt.
4. Alternately, you may have a dpkg service that’s still running. To find it, use the following command:
ps aux | grep -i dpkg
The dpkg output will look similar to the apt output.

3: Address the Stuck Apt Service
1. If you have a mystery apt or dpkg service running, terminate it and see if that resolves your error. Use the following command:
sudo kill 8808
2. Replace 8808 with the actual process ID (PID) from Step 2. It should complete and return to a new command prompt line. If it doesn’t, force the process to stop by adding the -9 option:
sudo kill -9 8808
This should have resolved the issue.
4: Delete Lock Files
The error message in Ubuntu may appear similar to the following:
/var/lib/dpkg/lock
/var/lib/dpkg/lock-frontend
/var/lib/apt/lists/lock
/var/cache/apt/archives/lock
These are lock files, which are created to prevent two instances of apt or dpkg from using the same files at the same time. This can happen if an installation is interrupted or did not complete. Remove the lock files at your own risk.
To delete the lock files, use the rm command:
sudo rm /var/lib/dpkg/lock
sudo rm /var/lib/apt/lists/lock
sudo rm /var/cache/apt/archives/lock
Removing these files should fix the error.
5: Reconfigure dpkg
1. Run the --configure command if you just deleted the lock files. Also, this command will help if you receive the following error:
“dpkg was interrupted, you must manually run ‘sudo dpkg –configure -a’ to correct the problem.”
2. Enter the command as displayed above:
sudo dpkg --configure -a
Output returns a new line and the command should resolve the issue.
Fix Could not get lock /var/lib/dpkg/lock-frontend Error
The steps for fixing this error follow the similar pattern in the methods we described above. The full error is:
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
1. Do not remove the lock files immediately. Before doing so, locate and kill all processes that may be using the files.
sudo lsof /var/lib/dpkg/lock-frontend
Note: Check out our guide to learn more about lsof command in Linux.
2. The output returns a result similar to:
lsof: WARNING: can't stat() fuse.gvfsd-fuse file system /run/user/1000/gvfs
Output information may be incomplete.
lsof: WARNING: can't stat() fuse file system /run/user/1000/doc
Output information may be incomplete.
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
unattende 1127 root 2oW REG 7,2 0 165231 /var/lib/dpkg/lock-frontent
3. If you see unattended under the command column, your system is installing a security update. Wait for the process to complete.
4. Otherwise, note all process IDs and kill them with the force option:
sudo kill -9 process_id
5. Once you do that, you can try removing the lock-frontend files.
sudo rm /var/lib/dpkg/lock-frontend
This should fix the error.
6. The last thing you can try after deleting the lock files is reconfiguring dpkg as we showed in the fifth section.
sudo dpkg --configure -a
To test if these steps fixed the error, run the update command:
sudo apt update
When the process completes successfully, that shows you fixed the “E: Could not get lock /var/lib/dpkg/lock” error.
Note: The error we tackled has multiple different forms, but the methods for fixing it are similar. Some of the variations of the “Could not get lock…” error are:
E: Could not get lock /var/lib/apt/lists/lock – open (11: Resource temporarily unavailable)
E: Unable to lock directory /var/lib/apt/lists/
and
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?
Conclusion
This article explains five options to fix the “E: Could not get lock /var/lib/dpkg/lock” error on Ubuntu.
One of the options above will resolve the issue and chances are that the error will resolve itself upon rebooting the system.
Another common Ubuntu error message «Sub-process /usr/bin/dpkg returned an error code (1)» could indicate a problem with the package installer.
Basically, I upgrade the software in the Ubuntu operating system after I am trying another software to update.
While I am entering Sudo apt-get update command getting below error in the terminal:
Error:
Unable to acquire the dpkg frontend lock in the terminal, here is the full error :
sreekanth@sreekanth-Inspiron-5537:~$ sudo apt-get install python3.7 E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable) E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
I tried to install python latest version using apt-get command, at the I am getting error like below snapshot.
Solution1:
Step 1: You can delete the lock file using below command:
sudo rm /var/lib/apt/lists/lock
sudo rm /var/cache/apt/archives/lock
sudo rm /var/lib/dpkg/lock
Like the below screenshot. I executed the below commands.
Then try to use apt-get command, if it is working fine then ok. Otherwise getting the same error then proceed with another solution. We will provide a simple solution for this type of issue [Solution 2].
Solution 2:
Here we will kill the process number then try to install the software simply.
Step 1: Getting process id from the terminal using below command:
pgrep -a apt
Step 2: Using kill command then kill that process id.
sudo kill -9 10799
After killed the upgrade process id then it’s working for me.
In Linux/Ubuntu operating system some of the users using Sudo apt-get command for installation, upgrading the software. At the time, we are facing the same error in the terminal. This type of error only forcefully stop the process while installing, upgrading the software, unfortunately, closed the machine while updating anything. At the time “unable to lock the administrator directory is another process already using it.” So here we will provide different types of solutions for this type of errors. The above solutions are enough for this type of error in the Linux/Ubuntu.
















