4

I made a systemd service that launches a simple .sh to read data from a serial connection. If I run the service manually after booting it works fine, but when I try to run it automatically at boot it fails because the .sh can't yet read from ttyUSB0 (awk: fatal: cannot open file /dev/ttyUSB0' for reading (No such file or directory).

Is there any way to make the service wait for ttyUSB0 and then run the .sh? I tried something like after=ttyUSB0 but that doesn't work.

[Unit] 
Description=Serial logger

[Service] 
ExecStart=/serial_script.sh

[Install] 
WantedBy=default.target
6

Consider using an udev rule instead of a systemd service to start your script.

Something like this in /etc/udev/rules.d/99-serial-logger.rules:

SUBSYSTEM=="tty", ACTION=="add", KERNEL=="ttyUSB0", RUN+="/serial_script.sh"

Or if you want to keep the script as a systemd service (e.g. to allow it to be controlled using the systemctl command), remove the WantedBy=default.target line from your service and make your udev rule like this:

SUBSYSTEM=="tty", KERNEL=="ttyUSB0", TAG+="systemd", ENV{SYSTEMD_WANTS}+="your-serial-logger.service"

As a result, udev should tell systemd to start your service when the device appears, and to stop it if/when the device is removed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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