It is known that fork() system call is used to create a new process which becomes child of the caller process.
Upon exit, the child leaves an exit status that should be returned to the parent. So, when the child finishes it becomes a zombie.
Whenever the child exits or stops, the parent is sent a SIGCHLD signal.
The parent can use the system call wait() or waitpid() along with the macros WIFEXITED and WEXITSTATUS with it to learn about the status of its stopped child.
(*)wait() system call : It suspends execution of the calling process until one of its children terminates.
Syntax of wait() system call:
pid_t wait(int *status);
(*)The waitpid() system call : It suspends execution of the calling process until a child specified by pid argument has changed state.
Syntax of waitpid() system call :
pid_t waitpid(pid_t pid, int *status, int options)
Note: By default, waitpid() waits only for terminated children, but this behavior is modifiable via the options argument such as WIFEXITED, WEXITSTATUS etc.
The value of pid can be :
- Less than -1 : Meaning wait for any child process whose process group ID is equal to the absolute value of pid.
- Equal to -1 : Meaning wait for any child process.
- Equal to 0 : Meaning wait for any child process whose process group ID is equal to that of the calling process.
- Greater than 0 : Meaning wait for the child whose process ID is equal to the value of pid.
WIFEXITED and WEXITSTATUS are two of the options which can be used to know the exit status of the child.
WIFEXITED(status) : returns true if the child terminated normally.
WEXITSTATUS(status) : returns the exit status of the child. This macro should be employed only if WIFEXITED returned true.
Below is a C implementation in which child uses execl() function but the path specified to execl() is undefned.
Let us see what is the exit status value of the child that parent gets.
Note : Above code may not work with online compiler as fork() is disabled.
Here the exit status is 127 which indicates that there is some problem with path or there is a typo.
Few exit status codes are listed below for extra information :
- 1 : Miscellaneous errors, such as “divide by zero” and other impermissible operations.
- 2 : Missing keyword or command, or permission problem.
- 126 : Permission problem or command is not an executable
- 128 : invalid argument to exit.
Note : The C standard does not define the meaning of return codes. Rules for the use of return codes vary on different platforms.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.