-1

code reads something like :

pid=fork()
if(pid){
    print parent_id
    print parent_id
}
else{
    print child_id
    print child_id
}

when it was executed it was 

child 
parent 
child 
parent

I don't understand how this could happen because child and parent should be printed consecutively.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • 1
    Please show real code and real output. Please ensure it is a complete [mre]. – kaylum Apr 21 '22 at 01:54
  • 1
    Try running it a few times. Since the two pieces of code are running in separate processes, the order should be somewhat random. – Solomon Ucko Apr 21 '22 at 01:55
  • The order in which the code runs in these two processes depends on the details of how your operating system's scheduler works, and you can't rely on it running in a particular way. – David Grayson Apr 21 '22 at 02:44
  • 1
    do note that `fork` has three different kinds of return values so your assumption about the parent may actually be the `error` return – user3629249 Apr 21 '22 at 03:26

1 Answers1

2

You probably have a mutli-core CPU, so both parent and child can both be running on separate CPU cores. Printing is slow enough that the parent process has time to gets its 1st print started before your child process's 2nd print starts.

Or if not, on a single-core machine then scheduling could context-switch after one print.

The whole point of fork is to create a 2nd process that's also running; there should be no expectation that their system calls don't interleave with each other.


Existing near-duplicates about fork race conditions / timing, although those primarily about which runs first, not any expectation of continuing to run for multiple system calls before the other process can do anything.

And more generally Understanding parent and child process execution order about making multiple system calls including read in both parent and child, causing one or both to block.

And two where people had the opposite problem: they expected interleaving of output but didn't get it. (Perhaps because of buffered I/O resulting in only one write system call, if run from an IDE with output connected to a pipe instead of tty perhaps.)

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847