Both logical AND (&&
) and logical OR (||
) operator employs short-circuiting behavior.
expr1 && expr2
: expr2
is not evaluated if expr1
is logical 0
(false).
expr1 || expr2
: expr2
is not evaluated if expr1
is logical 1
(true).
With logical short-circuiting, the second operand, expr2
, is evaluated only when the result is not fully determined by the first operand, expr1
.
Assuming all the fork()
calls in parent as well as child process are result in success, the tree of forked processes will be like this:
parent process
|
|
fork() // first fork
----- // below in the tree, RV is fork() returned value
|
|----child process [RV: 0]--
| |
[RV: child PID] |
| |
fork() && fork() fork() && fork()
------ ------
| |
| |--child process [RV: 0]--
| | |
| [RV: X (child PID)] |
| | 0 && fork()
| | // due to && short-circuiting behavior,
| | // fork() will not be called
| | |
| | Print "forked"
| | Exit
| |
| |
| X && fork() // X is a non zero value and hence the fork() will be called
| ------
| |
| |--child process [RV: 0]--
| | |
| [RV: child PID] |
| | |
| Print "forked" Print "forked"
| Exit Exit
|
|--child process [RV: 0]--
| |
[RV: X (child PID)] |
| 0 && fork()
| // due to && short-circuiting behavior, fork() will not be called
| |
| |
| Print "forked"
| Exit
|
X && fork() // X is a non zero value and hence the fork() will be called
------
|
|--child process [RV: 0]--
| |
[RV: child PID] |
| |
| |
Print "forked" Print "forked"
Exit Exit
I hope this will help you in understanding the execution. Try yourself for fork() || fork()
expression. Let me know if you have further questions.