Daemons in C - is there a way they're meant to

2019-05-07 09:30发布

问题:

I've got a general question about daemons in C, that I haven't seen an answer to by now.

Is there a way how one should implement the control of a daemon process, like a convention or standard?

--Rest is further explanation--

I have seen multiple documents teaching the basics how to create a daemon in C. Forking, closing file descriptors, changing root, etc... no problem. And they all stop, when the process enters a endless loop (when the daemon process is created - so to say). But this is only half the way when it comes to coding a daemon; you have to control it somehow. I can make it work different ways, but I have the feeling there is a lot more to it.

For this (checking if there is a process already running or for stopping a running daemon process, or ...) I have seen different approaches (UNIX sockets, file locks, pid-files, ...) with their pros and cons. But it seemed to me like opinions or personal flavors; "why don't you just...?" or "I've done it this way, it worked for me". And I am not sure if this is a sign of freedom or not.

I mean, if you take a look at sshd, httpd, syslogd, etc... they all can be controlled via init-scripts or the service command (start|stop|status). This looks like a standard. But is this just some loose convention a lot of people try to follow or is there some kind of "framework" in the deep sea of C functions? Do you have to make it work somehow - for example make your program respond to a "stop" argument and end the daemon process somehow? Or is there some kind of standard, convention, a UNIX-way, best practices... that one should follow to write "good, clean code" and that integrates well in most environments?

My main question comes down to: Is there a way it's meant to be done?

And if so, where could I find more information? I guess there is more to take care of, than just starting and stopping.

回答1:

There is no standard, but there is a de facto standard, as you have already noticed.

I suggest you take one of those examples, such as Apache, and look into what apachectl does. You'll find it sends signals to the daemon, based on knowing the PID, which it reads from a file.

In the case of Apache, signals make sense, because you don't want some kind of HTTP request to be able to stop the server. In the case of a DBMS, you might want to respond to incoming commands to stop the server, provided you authenticate and authorize first.



回答2:

You can use signals, or the daemon could create a unix socket (with appropriate permissions) and listen for data on in. It depends on how much control you need to implement over your program.

Remember that for low-traffic things, it can be convenient to use xinetd and let it fork and handle the connection, and just respond to the request.