Take the 2-minute tour ×

I understand fork, need help understanding why

if(fork() && !fork())

Does not evaluate the second fork procedure in the first child process.

Parent returns [X|x>0] ^ ![Y|y>0]
child.0 returns 0 and does not call second fork procedure
child.1 returns [X|x>0] ^ !0

Why does child.0 not call the second fork procedure?


share|improve this question

closed as not a real question by Oliver Charlesworth, Aniket, Andrew Barber, ybungalobill, hyde Feb 4 '13 at 21:38


You've already answered your own question; because of short-circuit behaviour of &&. –  Oliver Charlesworth Feb 4 '13 at 20:18
@OliCharlesworth Yeah, I was thinking the same thing... –  Ryan Amos Feb 4 '13 at 20:19

4 Answers 4

If the left operand of && evaluates to 0 (false), then the whole expression will evaluate to 0 (false) regardless of the value of the right operand, so the right operand isn't evaluated at all.

share|improve this answer

You are using && operator and if terminates immediately once evaluation returns 0. Basically, if executes from left to right and in the case of && operators termination is immediante once 0(or false) is encountered.

share|improve this answer

the second fork() is not called when the first fork() returns 0 because the boolean expression (0 && fork()) will always be 0, no matter what fork() returns. Therefore, to improve performance the second fork() is short-circuited and not executed.

share|improve this answer

The returned value of fork() is not what the child returns as you seem to think, when you say that child returns something. To check that you must use wait().

share|improve this answer
