Thread: Parent and child processes program variables

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    2

    Parent and child processes program variables

    I am writing a C program to demonstrate that parent and child program variables have the same initial values but are independent of each other. My code (below) produces output that I did not expect. The var1 and var2 variables that are changed in the child process are affected in the parent process. Can someone help me with this? These variables don't seem to be independent of each other, as the child process is changing the values in the parent.

    Code:
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    
    
    main()
    {
    	int status, var1, var2;
    	pid_t p, c;//create pid_t variables to hold pid values
    	var1 = 10;
    	var2 = 11;
    	c = fork();//create new child process
    	wait(&status);
    	switch(c)
    	{
    		//if c==-1 then error in forking
    		case -1: printf("Error in forking.\n");
    		
    		case 0: printf("Initial value of Var1 in child is %d\n Initial value of Var2 in child is %d\n", var1, var2);
    				var1 = 1;
    				var2 = 1;
    				printf("In child process:\nVar1 = %d\n Var2 = %d\n", var1, var2);
    		
    		default: printf("Initial value of Var1 in parent is %d\n Initial value of Var2 in child is %d\n", var1, var2);
    				 var1 = 2;
    				 var2 = 2;
    				 printf("In parent process:\nVar1 = %d\n Var2 = %d\n", var1, var2);
    	}
    	
    	exit(0);//exit
    };//end main

  2. #2
    Registered User
    Join Date
    Oct 2010
    Posts
    2

    Solved

    I wasn't using break statements..... And I was printing child in one of the parent print statements. HAHA

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 05-01-2011, 11:06 AM
  2. pipes between child and parent
    By blackmamba21 in forum C Programming
    Replies: 7
    Last Post: 12-08-2010, 08:36 PM
  3. Why isn't the execlp() function doing anything?
    By jsrig88 in forum C Programming
    Replies: 5
    Last Post: 10-12-2009, 10:09 AM
  4. Replies: 3
    Last Post: 10-15-2008, 09:24 AM
  5. process programming
    By St0rM-MaN in forum Linux Programming
    Replies: 2
    Last Post: 09-15-2007, 07:53 AM