DevHeads.net

How to implement a Linux daemon in bash that can be start/stop by `sudo service`?

Hi,

There are a lot of resource about creating Linux daemon. But I am not
sure which is one is the most correct and provide the essential things
for a Linux daemon in bash that can be start/stop by `sudo service`?
Would anybody point me the best resource to learn how to create such a
daemon? Thanks.

Comments

Re: How to implement a Linux daemon in bash that can be start/st

By Robert Heller at 02/11/2018 - 20:51

There are actually two parts to this.

One part is the daemon itself. Nomially, this is just a program that does
something in an endless loop, eg it could be waiting for network and/or UNIX
socket connections and processing them. Or it could be doing some periodic
task. In any case, it needs to do this "quietly" -- eg without doing I/O to
std in, out, or err (unless stderr is your log file). There are some "rules"
and tips about closing off stdin/stdout/stderr and "fading" into the
background (disassociating itself from a controlling terminal and becoming its
own process group head, etc.).

The second part has to do with what flavor of /bin/init is in use: SysV,
Upstart, or SystemD. Each of these has a different mechanism for dealing with
getting deamons started or stopped during boot up and shutdown. There are man
pages for that.

One of the best resources is to just pick a favored deamon see how someone
else did it. Find the source package and, to misquote Obiwan Kenobe, "Use the
Source, Luke"... :-) In many cases you can copy someone else's start/stop
script (or whatever) and make a small number of changes and there you are.