edited by
2,075 views
1 votes
1 votes
  • 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. 

edited by

Please log in or register to answer this question.

Related questions

2 votes
2 votes
3 answers
2
Philosophical_Virus asked Dec 10, 2023
765 views
Int main (){fork();printf("a");fork();printf("b");return 0;}How many distinct outputs are possible of above code? And also give outputs
3 votes
3 votes
1 answer
3
24aaaa23 asked Oct 1, 2023
719 views
Consider the following code segment :int main (void) { for (int i=2; i<=5; i++) { fork( ); }printf (“GOCLASSES”);How many times “GOCLASSES” is printed by the ab...
0 votes
0 votes
0 answers
4