Search code examples
clinuxprocessforkwait

The purpose of the wait() in parent c


I am new to processes in linux and c. I am using this straightforward example:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, const char * argv[]) {

pid_t child_pid_or_zero = fork(); //fork returns twice

if(child_pid_or_zero < 0)
{
    //if fork returns a number smaller than zero, something wrong happened
    perror("Something wrong happened\n");
    exit(-1);
}

if(child_pid_or_zero > 0)
{
    //if fork returns a number greater than zero, this is the parent process
    printf("I'm the parent, my pid is: %d\t My child pid is %d\n", getpid(), child_pid_or_zero);
    wait(NULL);
}

else
{
    //this means that fork now returned 0, the child process is running
    printf("I am the child with pid: %d\t My parent pid is: %d\n",child_pid_or_zero, getppid());

}


return 0;
}

If I were to omit the wait() method in the

if(child_pid_or_zero > 0)

What would happen? I tried this myself, and apparently, there was no immediate difference. Do we always need to use a wait(), or does this only apply when the child is supposed to perform heavy calculations etc ?

Thanks in advance.


Solution

  • Wait is for listening to state changes and obtaining information about the child. A state change is child termination, stopping or resuming by a signal. Wait allows the system to release the resources associated with the child. If a wait is not performed, then the terminated child remains in a "zombie" state.

    The kernel maintains a minimal set of information about the zombie process (PID, termination status, resource usage information) in order to allow the parent to later perform a wait to obtain information about the child. As long as a zombie is not removed from the system via a wait, it will consume a slot in the kernel process table, and if this table fills, it will not be possible to create further processes. If a parent process terminates, then its "zombie" children (if any) are adopted by init(1), which automatically performs a wait to remove the zombies.