Installable Linux daemons, how to create them in C++ ?
I have a server applicationin C++ which I want it to behave the same way as a Windows Service. Ie it should be started whenever the system is started independently of whether there is a user logged in or not. In Windows there are a lot of C++ classes able to facilitate communication with the Service manager and handle the start/stop/pause commands. What about Linux ? Also how can I easily deploy my application ? I envy the way how some applications get installed using the apt-get system command, is that easy to do with a custom application, say that I provide the binaries in one machine then automatically fetch them from the target Linux one ... ?
Thank you in advance for your help.
Ok, the first thing, you need to know that writing services in Windows and Linux is very different. First of all, in Linux, "services" are not called "services", they're called "daemons". Knowing that, you can use google to find this extremely useful document.
As for starting/stopping/restarting, there is no universal premade solution here. In most cases, daemons create *.pid files in /var/run; those files contain their process identifiers "PIDs". Then a simple bash script is written that controls the daemon execution by reading the pid from the appropriate file and sending a kill signal to it.
For example, suppose your daemon name is foo
. Then it will create the file /var/run/foo.pid and write its PID into it, using ASCII characters and appending a newline at the end. Your control script name would be fooctl
, it should support the following commands: start, stop and restart. That is, when you run fooctl start
, the script should first check if the corresponding pid file exists, if not, then do whatever is necessary to start the daemon; when you run fooctl stop
, it should read the pid from /var/run/foo.pid and kill the process with that ID. In case of fooctl restart
, your script will need to first stop the daemon, then start it again.
That all being said, it is just an agreement about how daemons should work. This is how it's usually done. But those rules are not enforced in any way. You are free to invent and use your own techniques for creating and controlling daemons.
As for the second part of your question (about apt-get), this is called package management. It has nothing to do with daemons, but since you asked: to do it with your custom application, you would need to publish it in the main repository, which might be impossible for a number of reasons; or you can create your own repo. Also you can assemble a *.deb package for your application and it will be just as easy to install. Search the web for more info on how to build packages for custom Linux applications.