on the way to C++ (unix-)daemons … : FILE* to iostream

Writing a unix daemon using C++, the idea might seem odd. But it’s desirable in many ways :

  • C++ provides a lot of methods which are inherently safe and neat regarding string treatments,
  • STL(sgi) provides a lot of nice containers, particularly the associative map,
  • convenient simple text input/output using iostream …

Now, coding a daemon implies a lot of very unix-native C details such as : properly detach from terminals, output some errors via syslog …

When one realises all those functionnalites have simple posix-C functions to take care of, a very convenient bridge from C to C++ is to bind a regular iostream to a FILE* descriptor.

Example : reading from a pipe using istream
The below posix-C function :

FILE *popen(const char *command, const char *type);

provides a very simple way to fork and read to (or write from) another process. The gnu iostream library documentation mentions some methods usable to turn FILE* into stream, but I would not say the said documentation made it straighforward. So here’s an example of such a pipe :

#include <errno.h>
#include <string.h>     // strerror

#include <iostream>
#include <ext/stdio_filebuf.h>  // __gnu_cxx::stdio_filebuf

using namespace std;

void filter_uggly_uppercase (istream &in, ostream &out) {
    char c;
    while (in && in.get(c)) {
        if ((c>='a') && (c<='z'))
            out << (char)('A' - 'a' + c);
        else
            out << c;
    }
}

int main (void) {
    const char *command = "find . -type f";

    FILE *f_pipe_in = popen (command, "r");
    if (f_pipe_in == NULL) {
        int e = errno;
        cerr << "error at piping from " << command << " : " << strerror (e) << endl;
        return 1;
    }

    // let's build a buffer from the FILE* descriptor ...
    __gnu_cxx::stdio_filebuf<char> pipe_buf (f_pipe_in, ios_base::in);

    // there we are, a regular istream is build upon the buffer :
    istream stream_pipe_in (&pipe_buf);

    // let's read from that pipe now, the usual way ...
    filter_uggly_uppercase (stream_pipe_in, cout);

    pclose (f_pipe_in);

    return 0;
}

No Comments

Sorry, the comment form is closed at this time.

macports and upgrading to mavericks

This is mainly a reminder of some light troubles encountered whilst upgrading from moutain-lion to mavericks. Certainly, many people could be concerned because Apple decided to give this upgrade for free (which is a good turn in my opinion). Most of the troubles come from the upgrade process, a fresh maverick installation might have much less problems. upgrading [...]
the_title(); ?>

tempelhof

one should scroll to the left, and then to the right.
the_title(); ?>
White Box - PurForm

White Box – PurForm

Grande narration noisy qui parcours le lisse, les moires, les coincidences géométriques, en son et en video.
the_title(); ?>
In C - Terry Riley - Orchestre de Bretagne

In C de Terry Riley par l’Orchestre de Bretagne

Exceptionnel : une oeuvre du courant minimaliste américain jouée en grandeur nature [...]
the_title(); ?>
our galaxy as seen from makhtech-ramon

Makhtesh Ramon, moonless night.

Makhtech Ramon is a huge erosion valley in the middle of negev desert. Stepping into a desert is really something worth trying, you'll have the sensation of being invited by nature to shortly visit a place where humans are not really supposed to be.
the_title(); ?>
James Lick refractor

James Lick refractor

a small blog entry to host the full-size original of this pic taken when I passed by mount hamilton and bumped into one’s child dream. this pic is currently illustrating wikipedia’s James Lick telescope entry. One may use it, conforming with Creative Commons attribution license.
the_title(); ?>
korg kaoss pad (by acidpix)

42

Utilisez le TLD 42 ! ce site est désormais accessible via : http://disjunkt.42/jd [...]
the_title(); ?>

bien nommer les choses

Dans la classique saga terremer, nommer les choses, plus précisement connaître leur nom, donne le pouvoir de les contrôler. Avec unix c’est pareil, connaitre le nom du point d’entrée d’un fichier exécutable permet de “l’invoquer“. Et ce depuis une ligne de commande, ou l’interieur de n’importe quel script ! C’est en étant appelés les uns [...]
the_title(); ?>
Hiroshi Yoshino, Charles Vannier, Kaya Sasaki, Hervé le Bitter.

Hiroshi Yoshino et Hervé le Bitter à la bascule

Duo de contrebassistes qui se rencontrent pour la première fois. Présentés l’un à l’autre par le danseur Charles Vannier, ils ont juste fait une balance de son de quinze minutes dans l’après midi. Ce fut donc une véritable improvisation. Comme à la bascule l’espace est petit, on est vite au courant de tout et la confession [...]
the_title(); ?>
bulgy capacitors - condensateurs gonflés/boursouflés

la peste des condensateurs, obsolescence programmée ?

Lorsque soudain un moniteur acheté un peu plus cher que la moyenne tombe en quasi-panne juste peu après les 3 années de garantie généreusement offertes par le constructeur, je maudis le sort. Et de rage je démonte, par acquis de conscience la bestiole. C’est qu’elle rendait une belle image, alors vraiment si je pouvais trouver [...]
the_title(); ?>