#include <stdio.h>
#include <unistd.h>
#include <signal.h>

char *Pidfile = NULL;
void pidfile_init(char *pidfile)
{
    Pidfile = pidfile;
}

void pidfile_set(void)
{
    FILE *fh;
    if(!Pidfile)
        return;
    fh = fopen(Pidfile, "w");
    if(!fh)
        return;
    fprintf(fh, "%d\n", getpid());
    fclose(fh);
}

void pidfile_free(void)
{
    if(!Pidfile)
        return;
    unlink(Pidfile);
}

int pidfile_get(void)
{
    int pid = 0;
    char buf[256];
    FILE *fh;

    if(!Pidfile)
        goto err;
    fh = fopen(Pidfile, "r");
    if(!fh)
        goto err;
    if(!fgets(buf, sizeof(buf), fh))
        goto err;
    fclose(fh);
    if(sscanf(buf, "%d", &pid) != 1)
        goto err;
    if(kill(pid, 0) < 0)
        goto err;
    return pid;
  err:
    return 0;
}

#ifdef _PIDFILE_TEST
int main(int argc, char **argv)
{
    int pid;
    pidfile_init("/tmp/pidfile.pid");
    pid = pidfile_get();
    if(pid) {
        printf("already running: %d\n", pid);
        exit(0);
    }
    pidfile_set();
    printf("pid %d running\n", getpid());
    pidfile_free();
}
#endif
