v2: - A few small fixed identified by Dan Berrange.
The original cover letter is below. Rich. Socket activation (sometimes known as systemd socket activation) allows an Internet superserver to pass a pre-opened listening socket to the process, instead of having qemu-nbd open a socket itself. This is done via the LISTEN_FDS and LISTEN_PID environment variables, and a standard file descriptor range. This patch partially implements socket activation. The limitation of this implementation is that qemu-nbd can only listen on a single file descriptor, and so if LISTEN_FDS > 1 (eg. for listening on multiple interfaces or ports) socket activation will fail. However for the simple case of listening on a single port, and either all interfaces with IPv4+IPv6, or just a loopback interface, the current implementation works fine. Fixing this properly would require considerable changes throughout qemu, since qemu's currently handling of getaddrinfo is plainly wrong. To use qemu-nbd from systemd, you create /etc/systemd/system/nbd.socket: [Unit] Description=QEMU Network Block Device server [Socket] ListenStream=10809 [Install] WantedBy=sockets.target and /etc/systemd/system/nbd.service: [Service] ExecStart=/usr/sbin/qemu-nbd -v -t /path/to/file and enable the socket service (only): systemctl enable nbd.socket systemctl start nbd.socket and then connecting to port 10809 will start qemu-nbd and service the file, with systemd opening the listening socket. In the ExecStart line, the qemu-nbd -v option is only needed if you want enhanced debugging. The -t option is required unless you want to fiddle with systemd settings for rate-limiting. If you try to use the -p and similar options with socket activation then qemu-nbd will give an error. (I wasn't sure where to document this -- there is no obvious documentation for qemu-nbd beyond the simple list of command line arguments) This is based on the implementations in libvirt (src/util/virutil.c:virGetListenFDs) and nbdkit (src/main.c:get_socket_activation), and also on Denis Plotnikov's implementation of --server-sock-fd (https://lists.gnu.org/archive/html/qemu-devel/2016-09/msg07781.html).