#include "daemon.h"

/* This sets up the program to run as a friendly daemon, something
   like a 'rig for silent runnning' function. ;) */
void daemonize(void)
{
	int i;

	for (i = 0; i < NOFILE; i++)/* close open file descriptors */
		close(i);
	chdir(DAEMONDIRECTORY);		/* change to our directory */
	if (fork())
		exit(0);				/* put self in background */
	setpgrp();					/* make self process-group leader */
	signal(SIGTTOU, SIG_IGN);	/* ignore all job-control signals, */
	signal(SIGTTIN, SIG_IGN);	/* SIGHUP, and SIGCLD */
	signal(SIGTSTP, SIG_IGN);
	signal(SIGCLD, SIG_IGN);
	signal(SIGHUP, SIG_IGN);
	tty_fd = open("/dev/tty", O_WRONLY);
	if (ioctl(tty_fd, TIOCNOTTY) < 0)
		exit(2);
	if (fork())
		exit(0);				/* and dissociate from terminal */
	nice(5);					/* be nice to your system */
	user_startup();				/* do any additional user-specified startup */
}
