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:
Since it is user service, running 'systemctl start/stop ...' from udev rule fails.
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:
SYSTEMD_WANTS
/SYSTEMD_USER_WANTS
, service should be start/stop using systemctl since start/stop does not match device add/remove.su
+ systemctl --user
is used.RUN
udev key should be either from /usr/lib/udev
or absolute pass must be used (man udev
).