Apt

如何檢查 apt lock 文件是否被鎖定?

  • November 19, 2019

我正在編寫一個腳本來執行一些apt命令,但我遇到了apt/dpkg數據庫被鎖定的潛在問題,因此我的腳本會退出。我想/var/lib/dpkg/lock在執行任何操作之前檢查鎖定文件(即),就像apt它執行命令時所做的那樣,但我無法弄清楚如何apt執行鎖定。

鎖定文件始終存在,並且apt-get不會在文件上進行群發。否則它將如何檢查它是否正在使用中?從strace我看到apt-get打開文件,但就是這樣。在我的腳本中,我可以在打開文件的同時apt-get打開它。

好吧,我認為這裡會有一個簡單的答案,但我找不到任何東西。首先,您是否 100% 確定鎖定文件始終存在?嘗試執行

lsof /var/lib/dpkg/lock

以root身份查看是否有任何程序將其打開。

根據我的閱讀,apt-get 做了一個 fcntl 鎖定,但我還沒有查看程式碼來驗證。我想這會解釋為什麼文件一直在那裡,只是根據需要鎖定它。

當你的腳本執行時檢查程序列表,如果同時執行 apt 則退出呢?這足以供您使用嗎?

看起來這個人走的路和你一樣,但沒有多大成功。

我來這裡是為了尋找類似於 gondoi 最終使用但用 Python 而不是 Ruby 編寫的解決方案。以下似乎運作良好:

import fcntl

def is_dpkg_active():
   """
   Check whether ``apt-get`` or ``dpkg`` is currently active.

   This works by checking whether the lock file ``/var/lib/dpkg/lock`` is
   locked by an ``apt-get`` or ``dpkg`` process, which in turn is done by
   momentarily trying to acquire the lock. This means that the current process
   needs to have sufficient privileges.

   :returns: ``True`` when the lock is already taken (``apt-get`` or ``dpkg``
             is running), ``False`` otherwise.
   :raises: :py:exc:`exceptions.IOError` if the required privileges are not
            available.

   .. note:: ``apt-get`` doesn't acquire this lock until it needs it, for
             example an ``apt-get update`` run consists of two phases (first
             fetching updated package lists and then updating the local
             package index) and only the second phase claims the lock (because
             the second phase writes the local package index which is also
             read from and written to by ``dpkg``).
   """
   with open('/var/lib/dpkg/lock', 'w') as handle:
       try:
           fcntl.lockf(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
           return False
       except IOError:
           return True

引用自:https://serverfault.com/questions/221871