Linux: Start daemon on connected USB-serial dongle

Philipp picture Philipp · Aug 27, 2013 · Viewed 13.7k times · Source

On my Linux (Angstrom distro on BeagleBone Black) I have a USB dongle which presents as a serial port and per default is available as /dev/ttyUSB0

I want to start a daemon, which will connect to the serial port and make it available as a socket. I have the code for this USB-to-socket bridge and it works when started by hand.

I want it to start automatically whenever the system boots, supposing the USB dongle is plugged in. How should I do this?

Attempts so far:

  1. systemd: I created a systemd service with conditions After: remote-fs.target and After:syslog.target , but (it seems) the USB dongle is not ready at that point and the startup of the daemon fails.

    Are there other systemd targets or services to condition to, so that the daemon is started only when the udev has finished installing devices and the network is ready?

  2. udev: I created a udev rule like

    KERNEL=="ttyUSB?", RUN+="/path/to/daemon.sh"

    which executes successfully. But the daemon (which is started as a background process with a "&" within that script) seems not to execute. Also it seems to be frowned upon, to fork long running processes from udev rules.

What is the correct way to do it?

Answer

Philipp picture Philipp · Aug 27, 2013

Create a udev rule like

# cat /etc/udev/rules.d/95-serialdaemon.rules
KERNEL=="ttyUSB0", TAG+="systemd", ENV{SYSTEMD_WANTS}="serialdaemon.service"

Create a systemd service like

# cat /lib/systemd/system/serialdaemon.service
[Unit]
Description=USB serial to socket bridge
After=remote-fs.target
After=syslog.target

[Service]
ExecStart=/mnt/serialdaemon.sh

Create the executable file

# cat /mnt/serialdaemon.sh
#!/bin/sh
date +%F-%T >> /var/log/serialdaemon.log
/usr/local/serialdaemon/serialdaemon -serial /dev/ttyUSB0 -port 15789 -baud 38400 >> /var/log/serialdaemon.log 2>&1
date +%F-%T >> /var/log/serialdaemon.log