in Operating System edited by
11,434 views
2 votes
2 votes

How many times "hello" gets printed?

main() {
    fork();
    fork();
    printf("hello");
}
in Operating System edited by
by
11.4k views

1 comment

@Bikram Sir I am not getting this call system pls explain .
1
1

2 Answers

8 votes
8 votes
Best answer

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
by

1 comment

@Debashish, how you use these types of graphics in your explanation??
4
4
Answer:

Related questions