About fork system call and global variables
- by lurks
I have this program in C++ that forks two new processes:
#include <pthread.h>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdlib>
using namespace std;
int shared;
void func(){
extern int shared;
for (int i=0; i<10;i++)
shared++;
cout<<"Process "<<getpid()<<", shared "
<<shared<<", &shared "
<<&shared<<endl;
}
int main(){
extern int shared;
pid_t p1,p2;
int status;
shared=0;
if ((p1=fork())==0) {func();exit(0);};
if ((p2=fork())==0) {func();exit(0);};
for(int i=0;i<10;i++)
shared++;
waitpid(p1,&status,0);
waitpid(p2,&status,0);;
cout<<"shared variable is: "<<shared<<endl;
cout<<"Process "<<getpid()<<", shared "
<<shared<<", &shared "
<<&shared<<endl;
}
The two forked processes make an increment on the shared variables and the parent process does the same. As the variable belongs to the data segment of each process, the final value is 10 because the increment is independent.
However, the memory address of the shared variables is the same, you can try compiling and watching the output of the program. How can that be explained ? I cannot understand that, I thought I knew how the fork() works, but this seems very odd..
I need an explanation on why the address is the same, although they are separate variables.