This is the direct result of short-circuit evaluation performed by logical &&
operator: when i != 3
, if
statement knows that the result of the expression is going to be false
, and stops right there.
That's why it does not get to execute fork
. If you do not want this behavior, you could use bitwise AND operator &
.
However, the logic of your code would remain questionable, because it would be impossible to tell on what side of the "fork" you landed when i != 3
.
If you want to do a fork
no matter what the value of i
, but properly get the side of the "fork", do the fork upfront, and check the result inside the if
:
pid_t side = fork();
if (i == 3) {
if (side == 0) {
...
} else {
...
}
} else {
if (side == 0) {
...
} else {
...
}
}