in Operating System edited by
2,105 views
1 vote
1 vote
  • 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. 

in Operating System edited by
by
2.1k views

6 Comments

Does the exit code here mean the return value or are they both different?
0
0

Here is some explanation

0
0
According to the manual, the exit status differs with the os. So exit status value has to be mentioned in the question, else how would we know which value to take
0
0

You can assume the Linux version and the following the sequence
 

child process:
    exit(x)         // 0 <= x <= 255
parent process:
    wait(&status);
    int res = WEXITSTATUS(status) // res = x

can be safely assumed considering this particular program.

1
1
left=right= getpid();

but where is getpid() function to initialize left and right value?
0
0
getpid() is actually a system call which is predefined and it returns the process id of the current process
0
0

Please log in or register to answer this question.

Related questions