Reputation: 71
I'm trying to figure why do this statement produce 2 processes
if(fork()&&(fork()||fork()))
printf("Hello");
I understand the short circuiting issue, and I know that if this statement was executed without if we will get 4 processes in total. So can you explain the criteria which is used by inserting if to a statement like this.
Upvotes: 2
Views: 81
Reputation: 16243
There should be 4 processes created. You can easily verify this by placing an extra printf
call after the if
statement.
The printf("Hello")
is only run twice, because the condition is only true for two of those processes.
Specifically, the root process spawns two child processes, and the second child process spawns one more :
<parent> : condition is true because the two first fork calls return non-0 : (true && (true || ??))
<child1> : condition is false because the first fork returns 0: (false && (?? || ??))
<child2> : condition is true because the first and third fork calls return non-0: (true && (false || true))
<child3> : condition is false because the second and third fork calls return 0: (true && (false || false))
Upvotes: 5
Reputation: 4763
Because the || statement returns true if the first fork() from inside resolves to true (different then 0 actually).
The && statement needs to know both the first fork and the 2nd fork.
So in your code
if (fork() && // this needs to be evaluated so it forks
(fork() || // this needs to be evaluated so it forks
fork() // the previous one was true, so this doesn't need to be evaluated
) )
So you will end up with two forks done.
Upvotes: 1