Kavan
Kavan

Reputation: 331

Confusion regarding fork() system call in C

I dont understand what is the difference between fork() & fork() and fork() && fork(). I also get different output for both of them.

fork() & fork();
printf("hi\n");

Output : hi
hi
hi
hi

fork() && fork();
printf("hi\n");

Output: hi
hi
hi

Can anyone please explain whats going on here. Is this an issue regarding compiler? (I am using gcc on ubuntu14)

Upvotes: 1

Views: 60

Answers (3)

3442
3442

Reputation: 8576

This is due to the && operator's short-circuit evaluation property. Basically, for any expression x && y, x is first evaluated. If the result is false, y is not evaluated at all and the whole expression evaluates into false. Otherwise, the result is that of evaluation y, casted as a boolean if necessary. So, for instance, false && printf( "Is this evaluated?\n" ) won't print anything.

This means that fork() && fork() will first evaluate the first fork(), and evaluate the second one if and only if the first one results in a non-zero result. In the particular case of the fork() function, this only happens in the parent process, since the child gets a 0 return status. Thus, the original parent forks twice, but the childs do not. The result is that only three processes will be spawned.

The & operator, on the other hand, has no short-circuit evaluation, since it's not a logical-AND, but a bitwise-AND. Since & is not about boolean values, but about bits (unlike &&), both arguments are always evaluated. This means that in the case of fork() & fork() the parent will fork twice, and the first child will fork again, resulting in four different processes.

BTW, you should be learning the C language rather than jumping straight to fork(). If you use a tool you don't understand issues like this will come back to haunt you quite often.

Upvotes: 1

pm100
pm100

Reputation: 50210

in fork() && fork() the first fork return 0. This means false and so the evaluation of the rest of the && clause is abandoned (it will be false regardless of the value of the rest of the clause)

The & version always evaluates (executes) both sides

Its like

 if (x != null && x->foo == 42)
    printf("42");

the second part (foo==42) is not touched if the first part (x!= null) is false

Upvotes: 1

David Hoelzer
David Hoelzer

Reputation: 16381

One is doing a logical test, the other is doing a bitwise and of the result.

 fork() && fork()

This will fork. In the parent, it will fork again because the first fork evaluates to a non-zero value (the pid) while in the child it will not.

 fork() & fork()

Both the parent and children will fork because this performs a bitwise and of the return value of the fork (either a PID or a zero).

Upvotes: 3

Related Questions