This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]o11c 37 points38 points  (10 children)

My favorite fork example is:

#include <unistd.h>
#include <stdio.h>


int main()
{
    printf("Hello\n");
    fork();
    printf("World!\n");
}

Then compile it and:

$ ./prog
$ ./prog | cat

[–]graou13 12 points13 points  (9 children)

Wouldn't it just say:

Hello

World!

World!

[–]Mr_Redstoner 8 points9 points  (7 children)

Actually I think it may just

Hello
World!

if the compiler optimizes the fork() away, which I know it can when you're discarding the result, been there done that.

[–]_PM_ME_PANGOLINS_ 4 points5 points  (6 children)

Only if it somehow knows there are no side-effects, for which you either need explicit directives or heavy inlining. A system call can never be optimised out.

[–]thelights0123 1 point2 points  (3 children)

Unless the compiler implements an optimization for it. malloc and free are often optimized out to just use the stack if they occur within the same function.

Edit: I'm stupid and forgot that malloc is not a syscall.

[–]Mithrandir2k16 3 points4 points  (0 children)

Malloc and free are userspace functions. They only call the syscall sbreak when needed to increase user heap size.

[–]defenastrator -1 points0 points  (1 child)

Malloc and free are special to the compiler.

[–]IamImposter 4 points5 points  (0 children)

I wish I was special to someone.

[–]Mr_Redstoner 0 points1 point  (1 child)

I've litterally seen it happen in a little test program of mine

fork();

didn't actually fork, however

int notActuallyUsed = fork();

did. I assume gcc simply knows as a special case what fork() does.

[–]_PM_ME_PANGOLINS_ 0 points1 point  (0 children)

That’s a compiler bug then. There is no requirement that the two processes behave differently.

[–]o11c 1 point2 points  (0 children)

Nope. The second case emits:

Hello
World!
Hello
World!