5

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.

AlvaroAV
  • 10,335
  • 12
  • 60
  • 91
charfeddine.ahmed
  • 526
  • 2
  • 8
  • 16

4 Answers4

14

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.

  • 1
    You don't need to publish your code. You can create your own repository with your (compiled) package if you wish. You just need to add you repository (and its signature key) into the apt system (/etc/apt/sources*). – ysdx Apr 20 '11 at 11:50
  • This is disastrous ! So basically the the start/stop will be done using the process id ?! So this is totally different from Windows where the service application sends callbacks to SCM then the SCM uses those callbacks for calling start/stop/resume etc. This means that I can't send a "pause" or "resume" command, and also since the stop will be performed using pid, my program wo'nt get the chance to clean things properly !! – charfeddine.ahmed May 24 '11 at 08:01
  • 4
    Of course you can pause or resume your daemons and you can do cleanup work before exiting. This is done with the help of signals. See this wikipedia article: http://en.wikipedia.org/wiki/Signal_%28computing%29 The "kill" command is used to send signals to your process and your process can interpret the signals as it wishes by using signal handlers (see here for an example: http://www.codeguru.com/forum/showthread.php?t=465662 ). –  May 24 '11 at 08:54
  • Oh that's relieving. Thank you. I was mistaken by various daemon examples which ignore such way of communication. – charfeddine.ahmed May 25 '11 at 08:02
  • 2
    @charfeddine.ahmed What Windows does or doesnt do is completely irrelevant since no-one really considers it a serious OS. Comparing Linux to Windows is like comparing Prague Castle to a poorly patched together thatch hut which has had a different group of misinformed hopefuls each term yanking straw out in random places and poking other straw in elsewhere until no-one really remembers if there was ever a plan and nor can anyone can see a road forward, so they just end up working out what consumers are bitching the most about and repackaging those components to align with the latest vogue. – ekerner Oct 28 '15 at 10:00
4

Try with this link .It contains A-Z daemon writing.

First off, you'll need the following packages installed on your Linux machine to develop daemons, specifically:

GCC 3.2.2 or higher and Linux Development headers and libraries

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>

int main(void) {
        
        /* Our process ID and Session ID */
        pid_t pid, sid;
        
        /* Fork off the parent process */
        pid = fork();
        if (pid < 0) {
                exit(EXIT_FAILURE);
        }
        /* If we got a good PID, then
           we can exit the parent process. */
        if (pid > 0) {
                exit(EXIT_SUCCESS);
        }

        /* Change the file mode mask */
        umask(0);
                
        /* Open any logs here */        
                
        /* Create a new SID for the child process */
        sid = setsid();
        if (sid < 0) {
                /* Log the failure */
                exit(EXIT_FAILURE);
        }
        

        
        /* Change the current working directory */
        if ((chdir("/")) < 0) {
                /* Log the failure */
                exit(EXIT_FAILURE);
        }
        
        /* Close out the standard file descriptors */
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
        
        /* Daemon-specific initialization goes here */
        
        /* The Big Loop */
        while (1) {
           /* Do some task here ... */
           
           sleep(30); /* wait 30 seconds */
        }
   exit(EXIT_SUCCESS);
}
Elshan
  • 7,339
  • 4
  • 71
  • 106
1

Deamons are process like others. Excepted that they have no parent (or their parent is process 0), no group id and no session id. Richard Stevens (whose Advanced Programming in the Unix Environment is still recommended when you are doing system programming under Unix) gives this function as a way to set up things:

if ( (pid = fork()) < 0) {
    return -1;
else if (pid == 0) {
    exit(0);

setsid();
chdir("/");
umask(0);

but it still doesn't handle some issues (closing of inherited file handles for instance, the subject is handled somewhere else in the book).

Then there is the problem of controlling the deamon. Some conventions are common (but not universal):

- writing its pid in a file under /var/run/
- handling SIGHUP as a way to reread its configuration file
- using the syslog system to log messages

Linux distributions have also common ways to control the deamons. Those are usually handled via scripts installed with the deamon, which translate the distribution conventions to what is precisely used by the deamon.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143
0

In linux, daemon is essentially interfaceless program. It has no special differences in code. Making a program to autostart as a daemon is, unfortunately, done in different ways on different distros. For Ubuntu, read about runlevels and upstart/plymouth system. You have to build a package file that does the setup for you, not the program.