Linux & Daemons
When you STFW about the Daemons,
Google defines daemons as A program that runs unattended to perform continuous or periodic systemwide functions .
There is a lot of documentation is available on the net about Daemon processes. This is a simple implementation of a Linux daemon in C..
/*********************************************************************************
File Name :my_daemon.c
Date :05.07.2007
Author :Maxin B. John <maxinbjohn at gmail.com>
Project Name :Simple Daemon
Version :1.0
Discription :This will create daemon process
History :
05.07.2007 : Created this file.
**********************************************************************************/
#include<stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
void myfun(void);
int nochdir, noclose;
/**********************************************************************************/
/* * Function name : main */
/* * Input Parameters : void */
/* * Return Type : int */
/* * Functionality : Starting the daemon process */
/**********************************************************************************/
int main()
{
int success ;
success =daemon(0,0);
if(success)
perror(“Daemon failed to executed \n”);
else
printf(“Daemon started. \n”);
}
/********************************************************************************************/
/* * Function name : daemon */
/* * Input Parameters : int nochdir , int noclose */
/* * Return Type : int */
/* * Functionality : Fork the task and start the daemon process */
/* */
/********************************************************************************************/
int daemon(nochdir, noclose)
{
int fd;
/* Startig the deamon process by calling fork(). 0 will be the child’s pid and hence the daemon process will start*/
switch (fork()) {
case -1:
return (-1);
case 0:
myfun();
break;
default:
_exit(0);
}
/*Disassociate from controlling terminal */
if (setsid() == -1)
return (-1);
/* defaults to / if nochdir is zero */
if (!nochdir)
(void)chdir(“/”);
/* ignoring the hangup signal */
if (signal(SIGHUP, SIG_IGN) == SIG_ERR)
{
perror(“signal(SIGHUP, SIG_IGN)”);
errno = 0;
}
if (!noclose && (fd = open(“/dev/null”, O_RDWR, 0)) != -1) {
(void)dup2(fd, STDIN_FILENO);
(void)dup2(fd, STDOUT_FILENO);
(void)dup2(fd, STDERR_FILENO);
if (fd > 2)
(void)close (fd);
}
return (0);
}
/*********************************************************************************/
/* * Function name : myfun */
/* * Input Parameters : void */
/* * Return Type : void */
/* * Functionality : Simple fuction to test daemon */
/* */
/*********************************************************************************/
void myfun(void)
{
/* This process should be running in background forever */
while(1){
printf(“Hello \n”);
sleep(2);
}
}
/********************************************************************************/