So the problem you're seeing here is because when
Type=forking is in use, then the pid file must be created (with the correct pid) before the parent process exits.
If you create the pidfile from the child, then it will race with the exit of the parent and in some (many?) cases will cause the first error you're seeing.
If you create the pidfile writing
$$ to it before you start the child, then it will have the pid of the parent, which will have exited, so you'll see the other error.
One way to do this correctly is to write the pidfile from the parent, just before exiting. In that case, write
$! (and not
$$), which returns the pid of the last process spawned in background.
# Run the following code in background:
while keep_running; do
# Write pid of the child to the pidfile:
echo "$!" >/run/daemon.pid
This should work correctly... HOWEVER, there's a much better way to accomplish this! Read on...
Actually, the whole point of systemd is to daemonize processes and run them in background for you... By trying to do that yourself, you're just preventing systemd from doing it for you. Which is making your life much harder at the same time...
Instead of using
Type=forking, simply write your shell script to run in foreground and set up the service to use
Type=simple. You don't need any pidfiles then.
/root/bin/daemon.sh to simply do this:
# Run the following code in foreground:
while keep_running; do
daemon.sh is not the best name for it at this point... Since that would imply it runs in background. Maybe name it something more appropriate, related to what it actually does.)
Then update the
.service file to use
Type=simple (which would actually be used by default here, so you could even omit it.)
ExecReload=/bin/kill -1 -- $MAINPID
ExecStop=/bin/kill -- $MAINPID
BTW, you can probably drop
ExecStop=, since killing the process with a signal is the default behavior as well...
Type=forking is really there only for legacy programs that only work that way and can't be easily fixed to work in foreground... It's hacky and inefficient. The whole point of systemd (and some of its alternatives, predecessors) is to do the forking and daemonizing itself and let services just worry about doing what they need to do! :-)
I hope you find this helpful... And I really hope you choose to let systemd do the heavy lifting for you! It's much more efficient that way.