Thread: Spawn Multiple child using fork()

  1. #1
    Anirban Ghosh
    Join Date
    Jan 2006
    Posts
    278

    Spawn Multiple child using fork()

    I am implementing the READERS WRITERS problem in C.
    I need to spawn multiple readers. I did the following.

    Code:
    #include <sys/types.h>
    #include <unistd.h>
    #include <stdlib.h> 
    #include <stdio.h>
    
    int main()
    {
    	pid_t R1, R2, R3, W1, W2, W3;
    	
    	R1 = fork();
    	R2 = fork();
    	R3 = fork();
    	
    	if(R1 == 0 || R2 == 0 || R3 == 0)
    	{
    		printf("\nI am child ... \n");
    		return 0;
    	}
    	else
    	{
    		printf("\nI am parent ... \n");
    		return 0;
    	}
    	
    	return EXIT_SUCCESS;
    }
    But I am getting weird output.
    I need to print exactly 3 times "I am child ... "
    and only 1 time "I am parent .. "

  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
    The child of R1 also creates R2 and R3
    The child of R2 also creates R3

    You have 3 children, and a hand-full of grandchildren as well.
    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.

  3. #3
    Anirban Ghosh
    Join Date
    Jan 2006
    Posts
    278
    So how shall I create say 3 readers and 3 writers with a common reader and writer function?
    Any help please?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 05-01-2011, 11:06 AM
  2. Replies: 4
    Last Post: 02-18-2010, 12:21 PM
  3. Replies: 3
    Last Post: 10-15-2008, 09:24 AM
  4. process programming
    By St0rM-MaN in forum Linux Programming
    Replies: 2
    Last Post: 09-15-2007, 07:53 AM
  5. fork(), exit() - few questions!
    By s3t3c in forum C Programming
    Replies: 10
    Last Post: 11-30-2004, 06:58 AM