What is the purpose of killing the parent process and leaving the child process running after fork ()?

I am reading Nginx Open Source and I am wondering why would someone kill the parent process and let the child process handle the rest of the program ? Why not just allow the parent process? Your help is greatly appreciated.

I am using Eclipse CDT to debug a program, and this is causing my debugging to stump as it continues to debug the parent process, not the child process (which actually handles the rest of the program).

Here's a snippet of code:

ngx_int_t
ngx_daemon(ngx_log_t *log)
{
    int  fd;
    switch (fork()) {
    case -1:
        ngx_log_error(NGX_LOG_EMERG, log, ngx_errno, "fork() failed");
        return NGX_ERROR;

    case 0:

        break;

    default:
    exit(0);

    }
/* Do stuff*/
}

      

EDIT: I understand that this procedure is meant to de-sime the program, but I'm still wondering why should we do this in the beginning?

+3


source to share


1 answer


The main part of deamonization of the program is to disconnect it from the control terminal.

For this, you call setsid()

.

setsid()

requires the caller not to be the leader of the process group (the process is started directly from a shell with job control).



If you fork

then continue in a child, the child will definitely not be the process group leader that allows the call to be made setsid()

.

Then you should repeat the fork + exit procedure to make sure the continuing grandson is not the session leader, ensuring that he is left without a controlling terminal (the session leader (established setsid()

) has the ability to acquire a controlling terminal, perhaps even accidentally by opening a terminal file).

+2


source







All Articles