Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of killing parent process and leave child process run after fork()?

I'm reading Nginx Open Source and I wonder why would someone kill the parent process and let child process handle the rest of the program? Why not just let parent process handle it? Your help is very much appreciated.

I use Eclipse CDT to debug the program and this causes my debug come to a dead end since it continues debugging the parent process, not the child process (which actually handle the rest of program).

Here is a snippet of the 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 procedure is for deamonizing a program but I'm still wondering why should we do that in the beginning?

like image 207
Toan Tran Avatar asked Dec 17 '25 13:12

Toan Tran


1 Answers

The main part of deamonizing a program is in disconnecting it from its controlling terminal.

To do that, you call setsid().

setsid() requires that the caller is not a process group leader (a process run directly from a shell with job control).

If you fork and then continue in the child, the child most definitely will not be a process group leader, which allows the setsid() call to succeed.

Afterwards, you should repeat the fork+exit procedure, to make sure the continuing grandchild is not a session leader either, ensuring it remains without a controlling terminal (a session leader (set by setsid()) has the ability to acquire a controlling terminal, perhaps even accidentally by opening a terminal file).

like image 76
PSkocik Avatar answered Dec 19 '25 03:12

PSkocik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!