Tuesday, October 27, 2009

Daemon Process



Linux just like another Unix system, it can create background process to run as daemon, daemonizing is simply a process created by another process as it's child, the parent fork() then exiting after creating the child, the child then detaching itself from the controlling terminal and run in background.

Linux provide daemon() system call, this call was born from BSD Unix, and not a POSIX standard function, this function mostly used by service-based applications such as httpd, sshd, udevd, etc. See daemon() for more informations, here the demonstration code on daemon() usage.
#include <stdio.h>
#include <unistd.h>

int
main(void)
{

int
i = 0;
FILE *fp;

i = daemon(1, 1);
if
(i == -1) {
perror("daemon");
return
-1;
}

fp = fopen("./daemon.log", "w+");
if
(fp == NULL)
exit(EXIT_FAILURE);
while
(1) {
fprintf(fp, "%i\n", ++i);
fflush(fp);
sleep(1);
}

/* never reach here */

fclose(fp);
return
0;
}