Thread: fork problems

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    36

    fork problems

    I have written the following.
    Code:
    #include <stdio.h>
    #include <unistd.h>
    #include <stdlib.h>
    
    int main(void) {
    	int i, pid;
    	pid = fork();
    	if(pid == 0)
    	{
    		int j;
    		for(j=0; j < 10; j++)
    		{
    			printf("child: %d\n", j);
    			fflush(stdout);
    		}
    		exit(0); /* Note that we do not use exit() */
    	}
    	else if(pid > 0)
    	{
    		int i;
    		for(i=0; i < 10; i++)
    		{
    			printf("parent: %d\n", i);
    			fflush(stdout);
    		}
    	}
    	else
    	{   
    		fprintf(stderr, "couldn't fork");
    		return;
    	}
    }
    When i run it, it prints 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9.
    My question is, shouldn't it print them mixed up?
    Shouldn't the parent and child process run in parallel instead of sequentially?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > Shouldn't the parent and child process run in parallel instead of sequentially?
    Over the long term, they will.

    But over such a short piece of code which takes a lot less than a single kernel tick, each process will get all it's work done in one kernel time slice.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problems with fork
    By raja9911 in forum C Programming
    Replies: 2
    Last Post: 02-03-2006, 07:48 AM
  2. Problems with execvp and fork....
    By LightsOut06 in forum C Programming
    Replies: 3
    Last Post: 10-09-2005, 06:34 PM
  3. fork(), exit() - few questions!
    By s3t3c in forum C Programming
    Replies: 10
    Last Post: 11-30-2004, 06:58 AM
  4. problems with fork() and execve()
    By kristy in forum C Programming
    Replies: 4
    Last Post: 12-21-2003, 08:18 AM