On fork() in Linux -
#include<stdio.h> int gictr0; int main(void){ int ipid; ipid = fork(); if (ipid == 0){ gictr0++; printf("in child\n"); printf("addr\t%x value\t%d\n",&gictr0,gictr0); } else{ gictr0+=2; printf("in parent\n"); printf("addr\t%x value\t%d\n",&gictr0,gictr0); } return 0;
}
the output ubuntu follows:
in parent addr 601054 value 2 in child addr 601054 value 1
the value proper , expected. how address of variable remain same in child , parent process? there wrong in code? please suggest.
memory addresses in unix-like vm system per-process. address obtain c
&
operator os-level construct, not addressing scheme maps directly bits in ram chips (or swapped-out vm pages). thus, it's possible same address in 2 different processes refer 2 different locations in "real" memory.fork
spawns clone of parent process. both processes continue operating had beforefork
, entire memory image of parent process copied create of child process... so, each process' perspective, memory addresses of variables still point same things did before. (but since processes separate, changes in 1 affect different underlying storage used other.)
Comments
Post a Comment