First of all, do not define a fork()
function in your code. fork()
is a system call already defined for you.
You call fork()
and once it (successfully) returns, you have two identical processes executing the next line of the code past the fork()
invocation. In the parent process fork()
will return the PID of the child; in the child process the return code is 0. based on this return code, your two processes can do whatever they intended to based on their roles.
Now, there is no guarantee on relative order of execution of these two processes. For all you know, child might not execute for the next 2 minutes and it would still be the correct behavior. So, this means you cannot expect the order of the output from both of those processes to be predictable.
Finally, change printf()
to fprintf()
to avoid buffering (which confuses things further in this case).