1,780 views
4 4 votes
what if the program like this(t1 is copied to all or printf will copied to all child)

main()

{

t1=0,t2=0;

t2=fork();

Fork();

Printf("Hi");

Fork();

t1=Fork();

Printf("hi");

}

Arjun sir , I don't know the buffer concept.please explain with tree method. How many child and how many time Hi printed.

4 Answers

Best answer
5 5 votes

20 "hi" will be printed  and 15 child process will be created , here is an image how to visualize it. The best way is to write value on branches, the parent is which have all the values of fork! =0;

sorry the right hand side will be the parent. i just misplaced it. well the concept is right.

• selected by
3 3 votes
For the first "hi" first 2 forks will work...

Hence 4 times "hi"

For the next "hi" all 4 forks will work

So 16 times "hi"

Total 20 times....
1 1 vote

t2 = fork()   ===== two processes (1 child + 1 parent)

fork()   ====    total 4 process at this point

hi       ====  4 hi printed

fork() =     processes becomes 8

t1= fork()   == ==  processes becomes  16

hi         == 16 hi

therfore total 20 "hi" printed

total processes = 16 (15 child , 1 parent)

0 0 votes
The answer to the question is

Child processes created = 15

No. Of times 'hi' is printed = 16

No. Of times 'Hi' is printed = 16

This is because every process has 1 hi and 1 Hi printed statement, and stdout is buffered (not printed immediately and carried/copied over to its child process) so both hi and Hi is printed for 16 times rather than 4 times.
Position:
Show:

Related questions

5 5 votes
2 2 answers
454
454 views
GO Classes asked Jul 15
454 views
Consider the following C program. Assume that every $\texttt{fork()}$ call succeeds.int main(void) { unsigned long int i; for (i = 0; i < 6; i++) if (fork() >= 0) continu...
3 3 votes
1 1 answer
311
311 views
GO Classes asked Jul 15
311 views
Assume that every $\texttt{fork()}$ call succeeds.int main() { int a = 0; int rc = fork(); a++; if (rc == 0) { rc = fork(); a++; } else { a++; } printf("a is %d\n", a); }...
4 4 votes
1 1 answer
306
306 views
GO Classes asked Jul 15
306 views
Assume that every $\texttt{fork()}$ call succeeds.int main() { int pid; pid = fork() && fork(); if (!pid) printf("A\n"); else printf("B\n"); return 0; }How many times are...
5 5 votes
1 1 answer
289
289 views
GO Classes asked Jul 15
289 views
Consider the following program. Assume that every $\texttt{fork()}$ call succeeds.int main() { int p1 = 1, p2 = 2, p3 = 3; p1 = fork(); if (p2 0) p2 = fork(); if (p1 0)...