Programming with Rudiments using the Base Classes

Using the daemonprocess Class

Here is some sample code for a daemon process that writes "hello" every 2 seconds. Most daemons don't write anything to the console, but this one does for purposes of demonstration.

@daemonprocess.C.html@ Using the file Class

...

@file.C.html@
Using the device Class

...

@device.C.html@
Using the serialport Class

...

@serialport.C.html@
Using the shmfile Class

...

@shmfile.C.html@
Using the Server Classes

Daemons are commonly used to serve data to clients on the same machine or over a network. Below is an example combining the daemon and listener classes. This server listens on unix and inet sockets for a client connection, receives a string from the client and writes the same string back to the client.

@server.C.html@

Notice that this server listens on both inet and unix ports. Inet ports allow clients and servers to talk across a network. Unix ports allow clients and servers on the same machine to talk through a pipe. Though clients and servers on the same machine could talk over inet ports, unix ports are much faster and use fewer system resources.

Using the Client Classes

Here's the code for a client that can talk to the server above. This client sends a string to the server, reads what the server sends back and prints it out. It does this once over an inet port and once over a unix port.

@inetclientsocket.C.html@ @unixclientsocket.C.html@ Using the Complex Initialization methods of the Server Classes

Setting up a server to listen on a socket is actually a multi-step process. The listen() methods simplify this process but some applications may require a more flexible interface. If you need to set socket options or perform additional actions between the steps of socket initialization, you can use the Complex Inititalization methods of the server classes.

Below is an alternative implementation of the myserver constructor in which some socket options are set.

myserver::myserver() : daemonprocess(), listener() {

        // run as a different user/group
        runAsUser("nobody");
        runAsGroup("nobody");

        // detach from the controlling tty
        detach();

        // initialize the ports
        inetsocket.initialize(NULL,8040);
        unixsocket.initialize("/tmp/mysocket",S_IRUSR|S_IWUSR);

        // set some socket options
        inetsocket.lingerOnClose(10);
        inetsocket.reuseAddresses();
        unixsocket.lingerOnClose(10);

        // bind to the ports
        inetsocket.bind();
        unixsocket.bind();

        // listen on the ports
        inetsocket.listen(15);
        unixsocket.listen(15);

        // add sockets to the pool
        addFileDescriptor(&inetsocket);
        addFileDescriptor(&unixsocket);
}
Using the listener Class

...

@listener.C.html@