Best approach to write a daemon

I want to write a daemon that will receive commands.

What it the best approach? I am thinking of two variants:

1. daemon to be a tcp server that will include a tcp client. Then from command line I can run
./daemon --command acommand (this will not start another daemon but will run the tcp client that will connect to the already started daemon and will send the command).

2. daemon to be a tcp server and to have another program that will be the client (a separate binary). And then I will run from command line the client that will connect to the server and send commands.

There's not much difference between those two variants, apache for example uses apachectl as the client. Many well known services use distinct client/server apps. But there are other that have the client embeded into them.

Is it weird to run from command line a daemon as a client?
 
Variant #1 can be fatal when daemon has setuid flag xD. Sure it can be fatal anyway if there is a setuid somewhere. Probably both tools must have the same libs (transport handling methods/objects), but I think it's a good way when you separate different use things.
 
Yeah, I'd separate the two too. And unless you really require remote access I'd use a local file socket instead of a network socket.

Also keep in mind to verify and validate everything that's sent to that socket. Don't trust anything even if you're sure it's from your own control program.
 
Regarding validation, yeah, I discovered that if I do not validate everything, I have errors hard to debug (for example broken pipe), and there are a lot of cases where something could fail. I've created wrappers for every function that I use in tcp/client apps, and the wrapper function return an error message if an error appear. And I've created few error functions, with different messages: some only display an error, others display and error and exit, others save core dump then exit.

Someone say that a UNIX program that works with system function is full of if cases, with every function to test for errors. Well that I've solved with wrappers.

And a convention can be used so for example if I create a wrapper for listen(2) function I can call it Listen (with only difference in name L insted of l).

This is the best approach I've found.

Thank you guys for your feedback. I will use then variant two.
 
C++ has a simple solution for all the validations, it is exception handling. Most other modern languages also have that. C doesn't. In other note, you should not use wrappers unless you keep calling exactly same segment of code several times in witch case its best practice not to have duplicate code. Keep in mind that wrappers make the code harder to read.
 
Back
Top