Creating a simple Rust daemon that listens to a port

Use https://docs.rs/daemonize/0.4.1/daemonize/ crate that takes care of most of this tricky stuff in creating a daemon for you?


What do they mean by this?

They mean that you shouldn't do anything fancy like forking to create a daemon program. Your program should just work, logging its operations directly into stdout, and init systems like systemd or launchctl will automatically handle everything else, including startup, shutdown, logging redirection, lifecycle management etc. Seriously consider this approach because it would make your program much simpler.

Creating a daemon process properly, though, is not simple. You have to fork the process, close and set up new file descriptors, tweak process groups, add signals handlers and more. Googling for something like "fork daemon" gives a lot of articles on how to create a daemon, and you can see that this is not an easy task. Certainly, you can do something like this in Rust, because it exposes all of the necessary system calls through libc crate. There can be some caveats, though: for example, I'm not sure how Rust runtime would react on fork() system call.

As for why your "daemon" fails when you use println!(), I suspect it happens because you detach from your child process and its stdio handles are automatically closed, and Rust I/O routines are not happy with that and trigger a task failure.