Is there a reason for this phenomenon or is it just random?
Neither C nor POSIX has any provisions that direct the particular output you observe, and likely you would see different results on some machines. In particular, different operating systems and operating system versions may differ with respect to whether parent or child first takes the CPU after a fork()
. (Even on a multicore system, only one of them can immediately take the core on which fork()
was executed.)
However, the two processes resulting from the fork do print using the same open file description in the kernel, and this means that they are actively prevented from writing to it at the same time. This is likely related to why you see long runs of the same output. One process obtains a lock, prints, releases the lock, and very soon after attempts to acquire the lock again. Under these circumstances there is a high probability that the same process reacquires the lock before the other can acquire it.
Additionally, it does take some time for a new process to actually get scheduled on a CPU. That probably explains the behavior I see for your program for inputs exceeding about 40, which is about 35 nonzero outputs, followed by fairly strict alternation between zero and nonzero, followed by all zeroes.
Of course, all of the above supposes that the two processes get scheduled concurrently at all. If you have only one core serving both then it naturally follows that each would produce long runs of its own output while it had the core. That could easily manifest as the two processes' outputs not being intermingled at all.
fflush()
to flush the incomplete lines? – Raptor