Explanation of C program output involving fork ()

The launch of this program is a "split"! 7 times. Can someone explain how "forked!" printed 7 times?

#include<stdio.h> #include<unistd.h> int main(){ fork() && fork() || fork() && fork(); printf("forked!\n"); return 0; } 
+4
source share
2 answers

Several concepts are used here, first of all, knowing what the fork does and what it returns in certain circumstances. Soon, when it is called, it creates a duplicate process of the caller and returns 0 ( false for logical expressions) in the child process and nonzero ( true for logical expressions) for the parent process. In fact, it can return a negative (non-zero) value in case of an error, but here we assume that it always succeeds.

The second concept is a short calculation of logical expressions such as && and || , in particular 0 && fork() will not call fork() , because if the first operand is false (zero) then there is no need to calculate the second. Similarly, 1 || fork() 1 || fork() will not call fork() .

Also note that in child processes, expression evaluation continues at the same point as in the parent process.

Also note that the expression is evaluated in the following order due to priority:

 (fork() && fork()) || (fork() && fork()) 

These observations should lead you to the correct answer.

Consider a simplified example fork() && fork()

  fork() / \ false true && fork() / \ false true 

So, here we have created three processes, two of which return false as the result, and one returns true . Then for || we have all processes returning false , trying to run the same operator again, so as an answer we have 2 * 3 + 1 = 7 .

+5
source

Unlike what I said in my comment, this is not about buffering. The fork process. The parent performs the second fork, and the child closes the second and performs the third. The first grandson evaluates the first && as false and performs the 3rd fork. This spawns 2 processes, one of which evaluates the 4th fork. Meanwhile (either before or after ... there is a race condition!), The other child became 3 processes when evaluating RHS || . Only 7 running processes. Draw a tree.

To simplify the calculation, consider:

 int f( void ) { int k; k = fork(); printf( "%d\n", (int) getpid()); fflush( stdout ); return k; } int main( void ) { f() && f() || f() && f(); return 0; } 
+4
source

All Articles