Skip to content

Handle file descriptors ​

Methods offered by the D-Bus API could return a file descriptor, which must be handled further. This is indicated by the :keep-fd parameter when calling the method (see dbus-call-method).

For example, Systemd includes a logic to inhibit system shutdowns and sleep states. It can be controlled by a the method ‘Inhibit’ of interface ‘org.freedesktop.login1.Manager’[1]. This function returns a file descriptor, which must be used to unlock the locked resource, some of which lock the system. In order to keep this file descriptor internally, the respective D-Bus method call looks like (what, who, why and mode are method-specific string arguments)

emacs-lisp
(dbus-call-method
 :system
 "org.freedesktop.login1" "/org/freedesktop/login1"
 "org.freedesktop.login1.Manager" "Inhibit"
 :keep-fd WHAT WHO WHY MODE)

⇒ 25

The inhibition lock is unlocked, when the returned file descriptor is removed from the file system. This cannot be achieved on Lisp level. Therefore, there is the function dbus--fd-close to performs this task (see below).

Note: When the Emacs process itself dies, all such locks are released.

Note: The following functions are internal to the D-Bus implementation of Emacs. Use them with care.

Function: dbus--fd-open filename ​

Open filename and return the respective read-only file descriptor. This is another function to keep a file descriptor internally. The returned file descriptor can be closed by dbus--fd-close. Example:

emacs-lisp
(dbus--fd-open "~/.emacs")

⇒ 20

Function: dbus--fd-close fd ​

Close file descriptor fd. fd must be the result of a dbus-call-method or dbus--fd-open call, see dbus--registered-fds. It returns t in case of success, or nil if it isn’t be possible to close the file descriptor, or if the file descriptor is closed already. Example:

emacs-lisp
(dbus--fd-close 25)

⇒ t

Function: dbus--registered-fds ​

Return registered file descriptors, an alist. The key is an open file descriptor, retrieved via dbus-call-method or dbus--open-fd. The value is a string object-path or filename, which represents the arguments the function was called with. Those values are not needed for further operations; they are just shown for information.

This alist allows to check, whether other packages of the running Emacs instance have acquired a file descriptor as well. Example:

emacs-lisp
(dbus--registered-fds)

⇒ ((20 . "/home/user/.emacs")
   (25 . "/org/freedesktop/login1"))

  1. https://www.freedesktop.org/software/systemd/man/latest/org.freedesktop.login1.html ↩︎