One process calls fork
, two processes return (errors notwithstanding). That's how it works. So the child starts from the next "line" (technically it starts with the assignment to r
).
What you're seeing here has to do with buffering. In the online case, you'll find that it's using full buffering for standard output, meaning the initial 5 hasn't yet been flushed to the output device.
Hence, at the fork, both parent and child have it and both will flush at some point.
For the line buffered case, the parent flushes on the newline so the line is no longer in the buffer at the fork.
The rules are explicit. Standard output is set to line buffered only if the output device is known to be a terminal. In cases where you redirect to a file, or catch the output in an online environment so you can sanitise it for browser output, it'll be fully buffered.
Hence why you're seeing a difference.
It's generally a good idea to flush all output handles (with fflush
) before forking.