in Operating System recategorized by
704 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
704 views

2 Answers

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
1 vote
1 vote
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.
Answer:

Related questions