11

I need to run some background processes that live as long as I am logged in with a certain user.

Does there exist something like a per-user daemon? I know only of global daemons that live from computer startup 'till shutdown (or manual startup/kill).

for now I made a script that checks if the process already exists and creates the process if it doesn't. This script is then run with the nohup command from my .profile. This way the process launches on startup, and is only launched once (even with multiple rxvt terms coming and going). Yet, it never gets killed after I log (which isn't a disaster but it is cleaner to also terminate the process).

romeovs
  • 1,680

3 Answers3

10

systemd allows users to run their own systemd instances to manage private daemons.

If you already have systemd installed, all you have to do is launch systemd --user and manage your services by running systemctl --user. User services will be searched for in ~/.config/systemd/user.

By default systemd will kill user services on logout (as you requested). This behavior can be altered by enabling lingering for a user with the loginctl --enable-linger $USER command.

Mor information can be found on the ArchWiki page.

aekojouz
  • 116
4

The dbus service is meant for precicely that ... ok, it can be used for precicely that :-). The per user dbus deamon is started when a user logs in to a desktop environment and is terminated when the user logs out (see man page of dbus-launch and the option --exit-with-session). A dbus service can be started together with the dbus instance or when the service's interface is called the first time through dbus. Each user can have its own dbus services specifications, defined in a hidden directory in the users home, or globally in /etc. See the dbus homepage on freedesktop for a lot of documentation and reference implementation.

I only use Debian based distros these days. All those have scripts in /etc/X11/Xsession.d which very often modify a string which at the very end will be evaluated as the command that starts the selected desktop environment. There is one such script for dbus, which prepends the command with the dbus wrapper dbus-launch. This wrapper launches a dbus-server and at least on vanilla Debian (and I'm willing to say "on all Debian based distros") dbus-launch is given the option --exit-with-session.

You should be able to wrap the processes you want run while a user is logged into a dbus service and IIRC dbus automagically takes care of terminating its services before exiting.

Bananguin
  • 7,984
2

If you are using BASH as your shell, you may try to do some detection in ~/.bash_logout and shut down the running process.

What you are probably looking for in the longer-term is interacting (e.g. via D-Bus) with something like ConsoleKit or systemd's logind.

peterph
  • 30,838