0

I have a problem with understanding this code in system programming using C in Unix.

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>

int main()
{
    pid_t pid;

    pid=fork();

    if( pid > 0)
    {
        /* parent */
        for( int i=0; i<1000 ;i++)
        {
            printf("\t\t Parent %d \n",i);
        }
    }
    else
    {
        /*child */
        for(int i=0; i<1000 ;i++)
        {
            printf("Child  %d \n",i);
        }
    }
    return 0;

}

When I executed it, it started to print parent 1 until 60, which means the pid is >0 so why it doesn't print parent until 999?

It switches between child and parent.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Please explain what your specific question is, and what you have tried to solve it / understand the problem. – Benjamin Feb 17 '17 at 04:46
  • That's normal. All processes get a chance to run in turn, so the parent gets to do some computing, then the child, then the parent again. If you have multiple processors, you might get them both running at the same time on different CPUs. Then there's the display technology; a terminal window is managed by a process too. – Jonathan Leffler Feb 17 '17 at 05:03
  • 1
    *It switches between child and parent.* This is exactly what `fork()` is intend for: **concurrent execution**. – Jean-Baptiste Yunès Feb 17 '17 at 06:09

0 Answers0