#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>

#define RUNNING_DIR "/tmp"
#define LOCK_FILE "/tmp/daemond.lock"
#define LOG_FILE "/tmp/daemond.log"

/*
 *       daemon.c
 *
 *       Copyright 2010 Vasudev Kamath <kamathvasudev@gmail.com>
 *     
 *       This program is free software; you can redistribute it and/or modify
 *       it under the terms of the GNU Lesser General Public License as published by
 *       the Free Software Foundation; either version 3 of the License, or
 *       (at your option) any later version.
 *     
 *       This program is distributed in the hope that it will be useful,
 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *       GNU General Public License for more details.
 *      
 *       You should have received a copy of the GNU General Public License
 *       along with this program; if not, write to the Free Software
 *       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *       MA 02110-1301, USA.
 */

void log_signal_message(char *filename,char *message){
    FILE *logfile;
    logfile = fopen(filename,"a");
    if(!logfile) return;
    fprintf(logfile,"%s",message);
    fclose(logfile);
}

int lfp;
void close_lock_file()
{
    close(lfp);
    remove(LOCK_FILE);
}

void daemonize(){
    int pid;
    int i;
    char str[10];

    pid = getppid();
    if(pid == 1) return;

    pid = fork();
    if(pid < 0) exit(1);
    if(pid > 0) exit(0);

    setsid();

    for(i = getdtablesize(); i >= 0; --i) close(i);

    lfp = open("/dev/null",O_RDWR);
    dup(lfp);
    dup(lfp);
    umask(022);

    lfp = open(LOCK_FILE,O_RDWR|O_CREAT,0640);
    if(lfp < 0) exit(1);
    if(lockf(lfp,F_TLOCK,0) < 0) exit(1);

    sprintf(str,"%d\n",getpid());
    write(lfp,str,strlen(str));

    atexit(close_lock_file);
}
