/*
** counter.c -- a simple counter for server-side includes
**
** On HPUX, compile with:
**      cc -Ae -o counter counter.c
**
** touch COUNTER_FILE before running.
**
** This program is public domain.
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

/* This is where the current count will be stored: */
#define COUNTER_FILE "/user/foo/public_html/.counter"

int main()
{
    FILE *fp;
    int fd, count;
    void set_file_lock(int fd, int function);

    close(2); dup(1);  /* make stderr same as stdout */

    if ((fp=fopen(COUNTER_FILE, "r+")) == NULL) {
        printf("<b>Can't open counter file!</b>\n");
        exit(1);
    }

    fd = fileno(fp);

    set_file_lock(fd, F_LOCK);

    fscanf(fp, "%d", &count);
    printf("%d", count);  /* send it to the page */
    count++;
    rewind(fp);
    fprintf(fp, "%d", count);

    rewind(fp);  /* need to rewind again to unlock the region */

    set_file_lock(fd, F_ULOCK);

    fclose(fp);

    return 0;
}

void set_file_lock(int fd, int function)
{
    if (lockf(fd, function, 0) == -1) {  /* set the file lock */
        printf("<b>");fflush(stdout);
        perror("lockf()");fflush(stderr); /* sync streams by flushing */
        printf("</b>");
        exit(1);
    }
}
