Tim
Tim

Reputation: 99408

Which of these two usages of `wait()` and `exit()` is better?

Here is some usage of wait() and exit() that I understand from https://github.com/karelzak/util-linux/blob/200769b6c0dff6863089ea2a9ff4ea9ccbd15d0f/login-utils/login.c#L939

f(){
    child_pid = fork();

    if (child_pid) { 
        // parent part
        ...
        while (wait(NULL) == -1 && errno == EINTR) ;
        ...
        exit();
    }

    // common part, which is actually child part
    ...
}

f();

// common part 2, which is actually child part
...

Is it the same as this?

f(){
    child_pid = fork();

    if (child_pid) { 
        // parent part
        ...
        while (wait(NULL) == -1 && errno == EINTR) ;
        ...
        exit();
    }

    if (child_pid == 0) { 
        // common part, which is actually child part
        ...   

        // common part 2, which is actually child part
        ...         
    }
}

f();

Is the second one more easier to understand than the first? That is what I feel (especially the above code is wrapped in a function, and a call to that function has other common code following it in main()), but I don't really know much about it.

Is there any reason or case where the first is better than the second? In particular, why does the implementation of login (the first link above) choose the first way?

Upvotes: 0

Views: 28

Answers (1)

manveti
manveti

Reputation: 1711

That's really a question of what belongs inside a function, which is somewhat nebulous. But if your function is something like "put me into a new process that has its environment set up in some particular way", then it makes sense for that code to have a structure like:

void switch_to_child(){
    int pid = fork();
    if (pid < 0){
        exit_with_an_error();
    }
    if (pid > 0){
        wait_and_exit_in_parent();
    }
    set_up_child_environment();
}

initialize_stuff();
switch_to_child();
do_child_stuff();

On the other hand, if your function is something like "spawn a new process to do something", it makes more sense for the code to have a structure like:

void make_child(){
    int pid = fork();
    if (pid < 0){
        exit_with_an_error();
    }
    if (pid == 0){
        do_child_stuff();
        exit_in_child();
    }
}

initialize_stuff();
make_child();
wait_and_exit_in_parent();

Upvotes: 1

Related Questions