- The
pid_t
data type is a signed integer type which is capable of representing a process ID.
getpid()
returns the process ID of the current process
- The
wait()
system call suspends execution of the calling process until one of its children terminates.
wait():
on success, returns the process ID of the terminated child. And $-1$ on failure.
wait(&status)
stores the exit code value of the child process in the status variable in a coded form.
WEXITSTATUS(status)
evaluates the actual exit code value of the child process.
For example, if the child exit code is $5$ then parent after executing the following code gives res = $5$
int status;
wait(&status);
int res = WEXITSTATUS(status);
// res = 5
What will be the output of the following program ___ :
pid_t root,wpid;
int solve(int n) {
if(n == 1 || n == 0) return 1;
pid_t left,right;
left = right = getpid();
left = fork();
if(left > 0) right = fork();
if(left == 0) return solve(n - 1);
if(right == 0) return solve(n - 2);
if(left > 0 && right > 0) {
int status,res = 0;
while((wpid = wait(&status)) > 0) {
res += WEXITSTATUS(status);
}
return res;
}
}
int main() {
root = getpid();
int res = solve(3);
if(getpid() == root) printf("%d\n",res);
exit(res);
}
PS : some of the system call and macro definitions are simplified for the sake of the QS as well as for simplicity.