Pages

Using fork-2: Fork with wait.

In the post "Fork-1 : Introduction" we saw how a child gets created using the fork call.
Every parent process which forks a child has to keep track of its child/children. When a child terminates, the parent has to be informed about the termination and only then the child and its resources can be deleted from the system.
To be able to keep track of the child the system call wait() is used by the parent. The wait series of system calls allows the parent to track the changes in the states of the child process.
If the parent does not call wait on its child, then the child that gets terminated goes into a zombie state, and will be removed from the system only when it is assigned a new parent and that parent calls a wait on it or the system is shutdown.
There are three kinds of wait calls
wait:



waitpid:



waitid



The following code creates a child and waits on the same using the wait() system call.
The value filled in the variable status denotes the return status of the child and can be inspected using various macros, one of which is WIEXITSTATUS. The code below uses this macro to print the inspected value of status.

fork_wait.c



Save it,compile and excute it.



Output:



The following code uses waitpid and waits on the child using its pid and prints the status returned using WIEXITSTATUS.

fork_waitpid



Save it,compile and excute it.



output:



The following code used waitid to wait on the child. One of the field of siginfo_t structure, which is filled with the information regarding the child by the system call, is the return status of the child.

The same is printed after the wait in the example below.

fork_waitid.c

Save it,compile and excute it.



Output:

The other flags and options which can be passed to the wait system calls are mentioned in the man page of wait.

No comments:

Post a Comment