daemon.c
author Markus Bröker <mbroeker@volpe.spectre.org>
Wed, 18 Aug 2010 16:17:00 +0200
changeset 142 d6bce20b455e
parent 138 dff18d1ac2af
permissions -rw-r--r--
asm/decimal.c: provide a default wordsize

/**
 * daemon.c
 * Copyright (C) 2008 Markus Broeker
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <signal.h>

#define      MAXLEN 80
#define    TIME_OUT 60

#define  INPUT_FILE "/proc/meminfo"
#define OUTPUT_FILE "/tmp/meminfo.log"
#define   LOCK_FILE "/tmp/.daemon.lock"

void check (int fd, char *buffer)
{
    char response[1024];
    char time_stamp[40];
    int len;

    time_t t;

    t = time (NULL);
    strftime (time_stamp, sizeof (time_stamp), "%a %d %T", localtime (&t));
    len = snprintf (response, sizeof (response), "%s %s", time_stamp, buffer);

    if (write (fd, response, len) == -1)
        perror ("write");
}

void sigproc ()
{
    if (unlink (LOCK_FILE) == 0)
        exit (EXIT_SUCCESS);
    exit (EXIT_FAILURE);
}

void sanity_check (int argc, char **argv)
{
    struct stat st;
    int fd;

    if (stat (INPUT_FILE, &st) != 0) {
        perror (INPUT_FILE);
        exit (EXIT_FAILURE);
    }

    if (argc == 2) {
        if (!strcmp (argv[1], "-h")) {
            printf ("Usage: %s [-f|-h]\n", argv[0]);
            printf ("Report bugs to mbroeker@largo.homelinux.org\n");
            exit (EXIT_SUCCESS);
        } else if (!strcmp (argv[1], "-f")) {
            if (unlink (LOCK_FILE) != 0)
                exit (EXIT_FAILURE);
        } else {
            fprintf (stderr, "Unknown Option %s\n", argv[1]);
            exit (EXIT_FAILURE);
        }
    }

    if (stat (LOCK_FILE, &st) < 0) {
        if ((fd = open (LOCK_FILE, O_WRONLY | O_CREAT, 0)) < 0) {
            perror (LOCK_FILE);
            exit (EXIT_FAILURE);
        }
        close (fd);
    } else {
        fprintf (stderr, "%s is already running\n", argv[0]);
        exit (EXIT_FAILURE);
    }

    fprintf (stderr, "%s monitors %s every %d seconds into %s\n", argv[0], INPUT_FILE, TIME_OUT, OUTPUT_FILE);
}

int main (int argc, char **argv)
{
    FILE *fin;
    static char buffer[MAXLEN];
    int fd;

    sanity_check (argc, argv);

    if (daemon (0, 0) == -1) {
        perror ("daemon");
        return EXIT_FAILURE;
    }
    signal (SIGTERM, sigproc);

    for (;;) {
        if ((fd = open (OUTPUT_FILE, O_WRONLY | O_CREAT, 0644)) < 0)
            return EXIT_FAILURE;

        if ((fin = fopen (INPUT_FILE, "r")) == NULL)
            return EXIT_FAILURE;

        while (fgets (buffer, sizeof (buffer), fin))
            check (fd, buffer);

        fclose (fin);
        close (fd);

        sleep (TIME_OUT);
    }

    return EXIT_SUCCESS;
}