Creating a daemon in C

#include 
#include 
#include 

/* based on code lighttpd:server.c source file */

void daemonize(void) {
        signal(SIGTTOU, SIG_IGN);
        signal(SIGTTIN, SIG_IGN);
        signal(SIGTSTP, SIG_IGN);
        if (0 != fork()) exit(0);

        if (-1 == setsid()) exit(0);

        signal(SIGHUP, SIG_IGN);

        if (0 != fork()) exit(0);

        if (0 != chdir("/")) exit(0);
}

int main(){

	int i;
        printf("Perhaps you want do something before go to background\n");
	scanf("%d", &i);

	daemonize();

	for (;;){
		sleep(10);
	}

}

One Comment

  1. TaQ says:

    Thanks for the code, just a little observation … the #includes are on the page source code, but they are missing on the visualization because they are not escaped and seen as HTML tags by the browser. :-)

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word