1
   #include<stdio.h>
    main() 
    {
     int a=9;
     printf(" %u hiii \n",&a);
     int p=fork();
     if(p==0){
             a=10;
             printf("\nChild  %u \n Value in child of a = %d\n",&p,a);
              }
     else
             printf("\nvalue of a = %d \n Parent with child process id = %d address of p = %u \n",a,p,&p);
     }

Ouptut of the above program According to ideone.com is - >

 3215698376 hiii 

 value of a = 9 

 Parent with child process id = 28150 address of p = 3215698380 

3215698376 hiii 

Child  3215698380 

Value in child of a = 10

My question is if both are processes are giving same addresses of variable 'a' then if I change the value the value in one process why isn't the change reflecting in Parent process. Moreover why the child process is running whole program else it should run with statements after fork().

devnull
  • 118,548
  • 33
  • 236
  • 227
user3111412
  • 177
  • 1
  • 3
  • 11
  • @devnull...But why the child process is running the whole.In my view it should run only after fork() as the Program Counter will have the address of next instruction. – user3111412 Jan 27 '14 at 13:37
  • Also, remember that `stdout` is line buffered. So adding the newline character at the end of the string you want to print should have the same effect as setting `stdout` unbuffered. – Alex Jan 27 '14 at 14:15
  • @Alex...but already i have entered a newline character so it should buffer the stdout. BUt by explicitly declaring explicitly setvbuf(stdout, NULL, _IONBF, 0); after 1st printf it not printing 1st printf in child process I am comfused !! – user3111412 Jan 27 '14 at 14:25

1 Answers1

2

The link in the question's comments answers the memory address question.

As for the "hiii" line being print out in both the parent and child application, the child is printing out the "hiii" line due to buffering of stdout. At the time of the fork() the line is still buffered in memory and not flushed to stdout until the next printf or the program exits. So the child really is starting execution at the fork line.

Try adding setvbuf(stdout, NULL, _IONBF, 0); as the first line of the program (or at least before the first printf) and see if the child still prints out the "hiii" line.

mshildt
  • 8,782
  • 3
  • 34
  • 41