Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm running Arch Linux, and I have a udev rule which starts a service when a device is inserted. In this case, it dials a connection when a 3G modem is plugged in.

KERNEL=="ttyUSB*", SYMLINK=="gsmmodem", TAG+="systemd", ENV{SYSTEMD_WANTS}="netcfg@wvdial.service"

However, if the device is removed, systemd won't stop the service, and hence when it is plugged in again, it won't start the service, since it's already running.

What I need is a matching udev rule which runs when the device is removed to stop the service.

Update

Using the answer below, what I now have is the following udev rule

KERNEL=="ttyUSB*", SYMLINK=="gsmmodem", TAG+="systemd", ENV{SYSTEMD_WANTS}="vodafone.service"

with the following service file (which was basically copied and pasted from the netcfg service file:

[Unit]
Description=Netcfg networking service for Vodafone Dongle
Before=network.target
Wants=network.target
BindsTo=dev-gsmmodem.device
After=dev-gsmmodem.device

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/netcfg check-iface wvdial
ExecStop=-/usr/bin/netcfg down wvdial
KillMode=none

[Install]
WantedBy=multi-user.target

I'm using netcfg-wvdial from the AUR to do the dialing.

share|improve this question
add comment

migrated from serverfault.com Jan 31 '13 at 12:46

This question came from our site for professional system and network administrators.

1 Answer

up vote 2 down vote accepted

Your problem may be solved using systemd solely, by simply specifying that your service Requires or, even better, BindsTo the given device.

Quoting:

"If one of the other [required/bound to] units gets deactivated or its activation fails, this unit [service] will be deactivated"

You just need to edit your service file like the following.

[Unit]
<...>
BindsTo=<DEVICE UNIT HERE>.device
<...>
After=<DEVICE UNIT HERE>.device

Note: to get a list of all available device unit files use systemctl list-units --all --full | grep ".device"

share|improve this answer
    
Does this mean that I don't need the udev rule? I tried to do as you suggested, by creating a new service file to replace the netcfg @wvdial.service and including those two lines. It does seem to stop the service now, but it doesn't start it when the device is plugged in again. –  crazystick Sep 19 '13 at 11:25
    
@crazystick you still need the udev rule for starting the service, what I meant is you won't need to use udev to stop it. –  brunocodutra Sep 19 '13 at 12:47
    
Got it. Works very nicely with both the udev rule and the modified service file. –  crazystick Sep 19 '13 at 12:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.