dzen2 pipe em C

Português

Este programa, escrito em C, exibe a porcentagem de memória RAM utilizada e também a data e hora. O programa roda o dzen2 e lhe fornece os dados por pipe. A atualização é de 10 em 10 segundos, mas pode ser alterada (mude o valor de sleep()). Use como base para adicionar outras informações que podem consumir muito mais CPU se implementadas em bash, por exemplo.

English

This C code displays the percentage of used RAM memory and current date and time. It launches dzen2 and communicates with it through pipe. The refresh rate is once per 10 seconds and can be changed by modifying the sleep() value. Use it as a starting point to implement other features that uses much more CPU when coded in bash, for instance.

#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

int usedMemPerc() {
    int procf;
    char buf[128];
    int total;
    int free;
    int temp;

    procf = open("/proc/meminfo", O_RDONLY);
    read(procf, buf, 128);
    close(procf);

    sscanf(buf, "MemTotal: %d kB", &total);
    sscanf(&buf[28], "MemFree: %d kB", &free);
    sscanf(&buf[56], "Buffers: %d kB", &temp);
    free += temp;
    sscanf(&buf[84], "Cached: %d kB", &temp);
    free += temp;

    return (int)( 100.0 * (total - free)/total + 0.5);
}

int main (int argc, char **argv) {
    int pfds[2];
    time_t dateTime;
    char strtime[128];

    pipe(pfds);

    /* child = loop */
    if (!fork()) {
        close(1);
        close(pfds[0]);
        dup(pfds[1]);
        while (1) {
            dateTime = time(NULL);
            strftime(strtime, 128, "%H:%M %a %Y-%m-%d", localtime(&dateTime));
            printf("mem: %d%% ^fg(white)|^fg() %s\n", usedMemPerc(), strtime);
            fflush(stdout);
            sleep(10);
        }
    }
    /* launching dzen2 */
    else {
        close(0);
        close(pfds[1]);
        dup(pfds[0]);
        execlp("/usr/bin/dzen2", "dzen2",
                "-p",
                "-e", "''",
                "-ta", "r",
                "-x", "975",
                "-fg", "#9999ff",
                "-bg", "#000000",
                "-fn", "-*-terminus-medium-*-*-*-14-*-*-*-*-*-*-*",
                (char *)NULL);
    }

    exit(0);
}

WikiLinux: MyDzen2 (last edited 2009-09-20 19:42:53 by CaduSantos)