Reputation: 249
I just can't figure out why this code works the way it does (rather than I'd expect):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
int main()
{
int buffer;
int* address;
address=&buffer;
if(fork()==0)
{
*address=27;
printf("Address %ld stores %d\n",(long)address,*address);
exit(0);
}
wait(NULL);
printf("Address %ld stores %d\n",(long)(&buffer),buffer);
return 0;
}
Why does the system store different variables even if they're pointed to the same memory address?
NOTE: I never really expected this code to work, since otherwise the whole bunch of pipes and stuff wouldn't make any sense; I'd just like to understand what's going on here.
Upvotes: 3
Views: 1990
Reputation: 886
From wikipedia: The fork operation creates a separate address space for the child. The child process has an exact copy of all the memory segments of the parent process.
So basically you create a new process with a different COPY of your original process memory. You change something on the duplicate process's memory, which is identical but a copy and expect to see it in the original. Normally, processes don't share memory directly.
Upvotes: 1
Reputation:
This isn't really a C question, it's about the behavior of (modern) operating systems.
In short: A userspace program on a modern OS runs in some private virtual address space. When accessing memory, the virtual address is translated to a physical address. The mapping between actual memory and virtual address space is set up by the operating system -- the memory is split into pages and a page can be "mapped" into the address space of a process.
fork()
typically just maps the same memory to the second process it creates, but as soon as this memory is written to, the page is copied and the copy is mapped ("copy on write"). A user space program will never see memory that is private to a different user space program.
I'm sure you can easily find more details searching for the key words given in this answer.
Upvotes: 6