1

I'm wondering that, when I'm using fork and creating several children and then the children are creating several children.

What should I do when a child finishes its task?

void foo(){
    pid_t childpid = 0;
    .
    .
    .

    while (..){

        childpid = fork();

        if ( childpid == 0)

            if(...)
                foo();
            else
                /* Do something */


    }
    while(wait(NULL) > 0);

}

This is very basic code because I'm trying to learning fork mechanism.

The question is: When the child's task is completed, what should I do? Should I use exit(0) for kill him or break?

If I use kill, valgrind gives me still reachable; if I use break, the process does not die and returns to the main function.

And second question: if child into first if condition, it calls foo again. Then there is a children in it. Should it wait or not?

What should I do?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
jundo
  • 66
  • 1
  • 10
  • 4
    You exit the child process like you exit the main process: Either by returning from the `main` function of by calling `exit`. If you don't want the child process to continue the loop in your `main` function, then a call to `exit` seems appropriate. – Some programmer dude Mar 09 '17 at 13:52
  • 1
    The recursive calls to `foo()` need to be coded with care — it isn't a common practice, but it might be correct for a given problem. (In my experience, it is much more likely incorrect than correct, but you might have a legitimate use case for creating children recursively.) If you're getting reports of leaked memory when you exit, you could arrange to call the clean-up code before calling exit so that memory is freed and files closed, etc. As to waiting, again, it depends on what is the desired behaviour. Note that a process can only wait on its own children, not on grandchildren. – Jonathan Leffler Mar 09 '17 at 15:38

0 Answers0