Thread: y does it run fork twice

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    29

    y does it run fork twice

    when i run this code i get the message "this is child1" twice.. its only suppose to run one time?? am i doing anything wrong
    Code:
    pid_t childpid1, childpid2; 
    int main()
    {
    printf("Create 2 processes\n");
    	childpid1 = fork();
        	childpid2 = fork();
    int i = 0;
    
    			if (childpid1 == 0 && i==0) 
            		{
    				printf("\nthis is child 1\0");
    				
    	    		};
    			if (childpid2 == 0 && i==1) 
            		{
            		printf("\nthis is child 2\0"); 
    			 };
    			
            exit(0); 
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > childpid2 = fork();
    Because this happens in parent AND child1

    > if (childpid2 == 0 && i==1)
    Because i is never anything other than 0

    > printf("\nthis is child 2\0")
    Strings always have a \0, so there's no point in adding another one yourself.

    Also, you're writing C99 code, but I don't suppose that matters to you.

  3. #3
    Registered User
    Join Date
    Jan 2006
    Posts
    29
    yeah i know i isnt anything else then 0, but this is was a test before i added it to my program. II i can see ur point that child 2 is a parent and a child....

    thanks... ill fix this straight away

    i got nooo idea what c99 code is.. so i guess it doenst matter

  4. #4
    old man
    Join Date
    Dec 2005
    Posts
    90
    Code:
    /* executable code above here */
    int i = 0;
    This kind of declaration is allowed in C99 but not in previous versions of ansi C (or K&R C). This isn't really an issue unless you try to use a compiler that doesn't support it, but it's nice to know these things in any case.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Understanding fork()
    By NuNn in forum C Programming
    Replies: 8
    Last Post: 02-27-2009, 12:09 PM
  2. Is fork() a resource hog?
    By HalNineThousand in forum Linux Programming
    Replies: 8
    Last Post: 04-15-2008, 09:07 AM
  3. Fork(), pause(), and storing PID's in a linked list
    By vital101 in forum C Programming
    Replies: 10
    Last Post: 09-28-2007, 02:16 AM
  4. fork problems
    By modec in forum Linux Programming
    Replies: 1
    Last Post: 10-21-2005, 12:48 AM