DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

C - Create Process Daemon

02.20.2006
| 22213 views |
  • submit to reddit
        // Create a process Daemon

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

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

int main(int argc, char *argv[])
{
	/*
	 * Funzione che mi crea un demone
	 */
	
	int pid;
	
	// create - fork 1
	if(fork()) return 0;

	// it separates the son from the father
	chdir("/");
	setsid();
	umask(0);

	// create - fork 2
	pid = fork();

	if(pid)
	{
		printf("Daemon: %d\n", pid);
		return 0;
	}
	
	/****** Codice da eseguire ********/	
	FILE *f;

	f=fopen("/tmp/coa.log", "w");
	
	while(1)
	{
		fprintf(f, "ciao\n");
		fflush(f);
		sleep(2);
	}
	/**********************************/
}