Sunday, December 13, 2015

Detaching a process from the terminal

Sometimes it is useful to detach your application from the console terminal. It may be because you're building a daemon or simply because you don't want the application closing when the user ends his terminal session.

Of course, you could leave it to the user to detach the application from the terminal, using nohup or screen commands, but it is always better not to rely on the user if you know you shouldn't be tied to a terminal session.

To detach a process from the terminal, in your C application, you must do the following:
#include <stdio.h>
#include <unistd.h>

int main ()
{
    pid_t cpid;
    cpid = fork();
    if (cpid == -1){
        printf("fork error\n");
        exit(1);
    }
    if(cpid > 0){
        exit(0); //parent exits
    }

    setsid();
    
    //do stuff

    return(0);
}
As an explanation: the main process is forked, the parent is exits and the child calls setsid to create a new session id for the process, so that it can behave as a stand alone process.

No comments:

Post a Comment