Consider this:
main()
{
int i = 1;
fork(); fork(); fork();
printf("%d ",i);
}
The output of the above code is:
1 1 1 1 1 1 1 1
That is, at the end there are 8 (2^3) processes reaching the printf()
line. Now consider the code below:
main()
{
int i = 1;
fork() && fork() || fork();
printf("%d ",i);
}
Initially, I thought there'd be no change in the output because the results of the comparisons using &&
, ||
are not being evaluated by a control statement like if
or while
. That is, they're being discarded. However, The output of this code is:
1 1 1 1 1
Meaning, at the end there are 5 processes that reach the printf()
line.
My question: What does this line do
fork() && fork()||fork();
Definitely, something has changed. I've never contemplated using comparison operators like &&
, ||
without control statements like if
, while
to evaluate the result of the comparison and accordingly take some action. I thought, without these control constructs, the comparison operators are meaningless; they'd simply return 1
or 0
without anything being done about it.
Clearly, I'm mistaken, and am totally unaware of this usage of the operators.
fork()
returns the PID for a child process if it’s returning in the parent, or 0
if it’s returning in the child. Logical operators short-circuit in C, so a && b
doesn’t evaluate b
if a
is 0
, and a || b
doesn’t evaluate b
if a
is not 0
.
So you fork once. Two processes. The right side of the &&
only gets evaluated in the child. Three processes. The right side of the ||
gets evaluated in the same child again. Four processes. But wait! &&
binds tighter than ||
, so the parent process also forks again, for a total of five processes.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments