Why fork() twice [duplicate]

All right, so now first of all: what is a zombie process?

It’s a process that is dead, but its parent was busy doing some other work, hence it could not collect the child’s exit status.

In some cases, the child runs for a very long time, the parent cannot wait for that long, and will continue with it’s work (note that the parent doesn’t die, but continues its remaining tasks but doesn’t care about the child).

In this way, a zombie process is created.

Now let’s get down to business. How does forking twice help here?

The important thing to note is that the grandchild does the work which the parent process wants its child to do.

Now the first time fork is called, the first child simply forks again and exits. This way, the parent doesn’t have to wait for a long time to collect the child’s exit status (since the child’s only job is to create another child and exit). So, the first child doesn’t become a zombie.

As for the grandchild, its parent has already died. Hence the grandchild will be adopted by the init process, which always collects the exit status of all its child processes. So, now the parent doesn’t have to wait for very long, and no zombie process will be created.

There are other ways to avoid a zombie process; this is just a common technique.

Hope this helps!

Leave a Comment