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

#include "file_lock.h"
#include "babysit.h"

int main(int argc, const char * const argv[]) {
    /* argv[1] is always set, so this is safe */
    const char *service_dir = argv[1];
    int fd;

    if (argc != 2) {
       fprintf(stderr, "Usage: %s [service_dir]\n", argv[0]);
       exit(100);
    }

    if (chdir(service_dir) != 0) {
        perror("chdir service_dir");
        exit(100);
    }

    fd = open(LOCK_FILE, O_WRONLY);

    if (fd == -1) {
        if (errno == ENOENT) {
            /* Files just don't exist, meaning babysit never ran here */
            exit(0);
        }
        else {
            /* Something else weird is up */
            perror("open lock file");
            exit(1);
        }
    }

    file_lock_init();
    if (file_lock(fd) != 0) {
        perror("file_lock");
        exit(1);
    }
    exit(0);
}


syntax highlighted by Code2HTML, v. 0.9.1