0

Systemd allows starting/stopping service from udev rule using SYSTEMD_USER_WANTS environment and StopWhenUnneeded option. But, service will be started when device is inserted and stopped when device is removed. What I need is vice versa:

  1. start service when device removed
  2. stop service when device inserted

Since it is user service, running 'systemctl start/stop ...' from udev rule fails.

V_V
  • 612
  • 9
  • 23

1 Answers1

2

udev rule for this question is

..., ACTION=="add", RUN+="/usr/bin/su USER -c 'systemctl --user stop my-service'"
..., ACTION=="remove", RUN+="/usr/bin/su USER -c 'systemctl --user stop my-service'"

The important points are:

  1. Instead of SYSTEMD_WANTS/SYSTEMD_USER_WANTS, service should be start/stop using systemctl since start/stop does not match device add/remove.
  2. To start/stop service from other user su + systemctl --user is used.
  3. Program pass to RUN udev key should be either from /usr/lib/udev or absolute pass must be used (man udev).
V_V
  • 612
  • 9
  • 23