Rust Daemon best practices Rust Daemon best practices unix unix

Rust Daemon best practices


Following the messages in the comments, I decided to use a systemd service rather than creating my own daemon. This seems to be an ideal way to manage background tasks. I've edited the top code so that it makes sense with the answer.

Systemd - linux

You will need to create a .service file and place it in your systemd daemon directory. For example: /etc/systemd/system/test.service

Then update the file rights:

sudo chmod 644 /etc/systemd/system/test.service

To start your service:

sudo systemctl start service_name

Service Code:

[Unit]Description=Test serviceAfter=network.targetStartLimitIntervalSec=0[Service]Type=simpleRestart=alwaysRestartSec=1User=usernameExecStart=/usr/bin/env test[Install]WantedBy=multi-user.target

Launchctl - macOS

For macOS we need to create a .plist file and place it in the launch daemons directory. For example: /Library/LaunchDaemons/test.plist

Next update the permissions on the file:

sudo chown root:wheel /Library/LaunchDaemons/com.test.daemon.plist

Load the daemon:

launchctl load /Library/LaunchDaemons/com.test.daemon.plist

Start the daemon:

launchctl start /Library/LaunchDaemons/com.test.daemon

Plist code:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN"    "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>    <key>Label</key>        <string>com.test.daemon</string>    <key>ServiceDescription</key>        <string>Test Server</string>    <key>ProgramArguments</key>        <array>                         <string>/Users/tom/desktop/test/target/debug/test</string>        </array>    <key>RunAtLoad</key>        <false/></dict></plist>