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