This question already has an answer here:

I always thought that child processes were always executed after the parent process was completed but after running the following program i get results like sometimes only printing parent or child or alternate at first i thought it was the scheduler that was changing the processes but in the task manager even if both are on S state they are still printing so when child processes are executed and when the parent Thank you!

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main (){
    int pid=fork();
    while (1){

marked as duplicate by Stephen Kitt, telcoM, Jeff Schaller, roaima, Rui F Ribeiro May 21 '18 at 21:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Here are some full stops you can use to separate your sentences . . . . . . . – roaima May 21 '18 at 16:54

After a fork(), both the parent and the child start running, theoretically simultaneously. Of course in practice, they'd alternate if you're on a uniprocessor system, or there are other processes that want to run, or if the system's scheduler says so for some other reason.

The behaviour of simultaneous busyloops like you have in your example is likely to be very sensitive to how the scheduler reacts to things outside your program. So not something you want to rely on.

If you add an explicit sleep(1) inside the loop there, you should see more consistent behaviour. Or, if you really want two processes doing something in alternation, as fast as they can, you'll need to implement some sort of synchronization.

  • So the scheduler is the one who is making the change who will be executed between the parent and the child process in this case scenario ? – Laur155 155 May 21 '18 at 16:19
  • i change the priority of the two processes (child>parent) its start:parent-child repeated ,after some time the child becomes more frequent but there times where it goes again parent-child,and sometimes its only parent however it for a short period of time. – Laur155 155 May 21 '18 at 19:15
  • @Laur155155, yes. They run at the same time, or close enough. And since there's no explicit synchronization (locking) or dependencies between them (one would wait for input from the other), you can't predict what order they will run in. And you shouldn't try to. In a practical real-world implementation you'd have explicit ordering, or you'd implement it all in a single process, so that it could do whatever necessary tasks in-order. – ilkkachu May 21 '18 at 20:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.