Running this program is printing “forked!” 7 times. Can someone explain how “forked!” is being printed 7 times?
#include<stdio.h>
#include<unistd.h>
int main(){
fork() && fork() || fork() && fork();
printf("forked!\n");
return 0;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’re several concepts being used here, first one is knowing what
forkdoes and what it returns in certain circumstances. Shortly, when it gets called, it creates a duplicate process of the caller and returns0(falsefor logical expressions) in child process and non-zero (truefor logical expressions) for parent process.Actually, it could return a negative (non-zero) value in case of an error, but here we assume that it always succeeds.
The second concept is short-circuit computation of logical expressions, such as
&&and||, specifically,0 && fork()will not callfork(), because if the first operand isfalse(zero), then there’s no need to compute the second one. Similarly,1 || fork()will not callfork()neither.Also note that in child processes the computation of the expression continues at the same point as in the parent process.
Also, note that the expression is computed in the following order due to precedence:
These observations should lead you to the correct answer.
Consider the simplified example of
fork() && fork()So here we have three processes created, two of which return
falseas the result and one returningtrue. Then for||we have all the processes returningfalsetrying to run the same statement again, so we have2 * 3 + 1 = 7as the answer.