in Operating System recategorized by
1,468 views
0 votes
0 votes

How many times the word "PROCESS" will be printed when executing the following program ?

main(){
    printf("PROCESS");
    fflush();
    fork();
    fork();
}
  1. $8$
  2. $4$
  3. $6$
  4. $7$
in Operating System recategorized by
by
1.5k views

2 Comments

anyone can try it here https://www.programiz.com/c-programming/online-compiler/

It’s printing only once, and that option it self is not there.

I hope whoever conducted the exam had corrected the key

1
1
hope so :)
0
0

2 Answers

2 votes
2 votes
Best answer
The options here are wrong. The word will be printed only once, which will be done by the parent or main thread. the fork() instructions are executed after printf so nothing will be printed by the child processes.
selected by
2 votes
2 votes
OPTION  B

The number of times "PROCESS" is printed is equal to number of process created. Total Number of Processes = $2^{n}$, where n is number of fork system calls. So here$ n = 2, 2^{2} = 4$

fflush() is typically used for output stream only. Its purpose is to clear (or flush) the output buffer and move the buffered data to console (in caseof stdout) or disk (in case of file output stream).

The two fork() calls create $3$ child processes, and hence "PROCESS" will be executed $4$ times if we don't use fflush.

If we put a '\n' at end of printf or use fflush(stdout); only $1$ printf will be done.

2 Comments

From man page: “If the stream argument is NULL, fflush() flushes all open output streams”

So, why fflush(stdout) is different from fflush() here?
1
1
A simple fflush() throws error: too few arguments to function ‘fflush’.

Also, if we do fflush(NULL) the word PROCESS still gets printed only once, as its printing precedes fork();
0
0
Answer:

Related questions