daemon.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Fri, 05 Mar 2010 22:03:16 +0100
changeset 112 9bfb339a8156
parent 79 1499176750b9
child 131 b5ad49852adc
permissions -rw-r--r--
respect the prototype committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * 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);

    write (fd, response, len);
}

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 (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) {
        fd = open (LOCK_FILE, O_WRONLY | O_CREAT, 0);
        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);

    daemon (0, 0);
    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;
}