edited by
11,529 views

2 Answers

Best answer
8 votes
8 votes

General formula for this fork() related problem is :

Total number of process created = { (2n) -1)+1 }

where (2n) -1 = number of Child Process  and 1 is for Parent Process. 

and n = number of time fork() is called.

here n = 2 

so  number of child process is = (2n) -1 = 4 - 1 = 3 and parent process is 1

so output is 3+1 = 4 [ (2n) -1)+1  = 4]

4 times  hello would be printed.

hello

hello

hello

hello

here 4 is number of process created among which 3 are child process and 1 is parent process.

selected by
8 votes
8 votes

check how fork() works

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main() {
	int status;
	pid_t a,b;
	
	a = fork();
	b = fork();
	printf("Hello\n");
	if(a = 0 && b > 0) {
		wait(&status);
		exit(0);
	}
	if(a > 0 && b > 0) {
		while(wait(&status));
		exit(0);
	}
	exit(0);
}

/*
Hello
Hello
Hello
Hello
*/
edited by
Answer:

Related questions

2 votes
2 votes
3 answers
2
Philosophical_Virus asked Dec 10, 2023
888 views
Int main (){fork();printf("a");fork();printf("b");return 0;}How many distinct outputs are possible of above code? And also give outputs
0 votes
0 votes
1 answer
3
Erwin Smith asked Apr 11, 2023
782 views
void main() { int n = 1; if(fork()==0) { n = n<<1; printf(“%d, “, n); n = n <<1; } if(fork()==0) n=n+700; printf(“%d, “,n); }Which of the following output is not ...