azrahel
azrahel

Reputation: 1213

How to daemonize a process in C using fork() func. - socket programming

i ve searched quite a lot already and am aware that maybe i already came across some helpful answers but were unable to understand them...not really much of a programmer i am: )

the case is i would like to implement a daemon - background process totally independent of what is happening in the meantime - to parse data which are being received from the server (am writing IRC client) but to do it in non-blocking way using select().

Here s fragment of my code. But i cant get to printf under the comment //rest of the program

i hope it s understandable enough.

pID=fork();
        if(pID < 0){
            //failed to execute fork()
            perror("Error while forking");
            getchar();getchar();
            exit(1);
        }
        if(pID > 0){
            exit(0);
            }
        //child down here
            umask(0);
            //setting new session
            sID = setpgid(0,0);
            if(sID < 0){
                perror("Error while setting new session");
                getchar();getchar();
                exit(1);
            }
            while(1){
                sleep(1);
                if((readReady = readReadiness(sockfd))==0)
                    continue;
                else{
                    //here am going to recv() data from server
                    printf("I am child and parsing\n"); //testing if its in background -i would like it not to print to stdout (run in background)

                }
            }


        //rest of the program down here
        printf("Why isnt it printing to stdout ??\n");

should i use grandchild ? (double forking ?) or... ?

Thanks in advance

Upvotes: 0

Views: 1349

Answers (1)

William Morris
William Morris

Reputation: 3684

My comment above was neither answer nor suggestion; it was a question.

I don't see why you need to fork again - you have a process without a controlling terminal (thanks to setpgid) as you desire. You can process received data in the while(1) loop. Looks like you are set to go - the 'rest of the program' goes in the while loop.

EDIT

Calling fork creates a child copy of the running process. Calling setsid in the child will disconnect the child from the terminal but will not affect the parent (which exits anyway). I suggest you start off with something like:

static void
process_stuff(int sockfd)
{
    while (1) {
        /* receive data on socket and process */
    }
}

void
run_daemon(int sockfd, int foreground)
{
    if (!foreground) {
        if (fork()) {
            exit(EXIT_SUCCESS); /* parent */
        }
        /* child */
        setsid();
    }
    process_stuff(sockfd);
}

The reason for having the if (foreground) clause is that it allows you to debug the server in the foreground under gdb when it doesn't work.

Upvotes: 2

Related Questions