#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
int n=5;
pid_t pid = fork();
if(pid==0)
{
printf("PRIMA FIGLIO %p\n", &n);
printf("PRIMA FIGLIO %d\n", n);
n+=15;
printf("DOPO FIGLIO %p\n", &n);
printf("DOPO FIGLIO %d\n", n);
}
else
{
printf("PRIMA PADRE %p\n", &n);
printf("PRIMA PADRE %d\n", n);
wait(0);
printf("DOPO PADRE %p\n", &n);
printf("DOPO PADRE %d\n", n);
exit(0);
}
}
It prints:
1 2 3 4 5 6 7 8
PRIMA PADRE 0x7fff3c74d538
PRIMA PADRE 5
PRIMA FIGLIO 0x7fff3c74d538
PRIMA FIGLIO 5
DOPO FIGLIO 0x7fff3c74d538
DOPO FIGLIO 20
DOPO PADRE 0x7fff3c74d538
DOPO PADRE 5
the fork() call duplicates a process scope of addresses, in fact father and child have different values for the variable n, so I expected addresses to be different
I don't think that is correct, glennhk. The fork() call creats a new process, but it does not initialize it from a new program standpoint. Instead, the new processes' instruction, user-data, and system-data segments are almost exact copies of those of the old process ("Advanced Unix Programming" - Marc Rochkind ISBN 0-13-011818-4.)
Yes, fork() copies the (virtual) memory map of the parent to the child, such that child and parent both refer to the same physical pages of memory until a write occurs.
I already know the copy-on-write technique, but I expected to see a change of address after the n+=15 statement because child and parent have different addresses.
I'm getting too old - I totally mis-read what jsmith said. They initially share the addresses until a write occurs. The reason the addresses appear the same is based upon when the output is written. Perhaps also printing out a timestamp or having the child process sleep for a bit would show this.
jsmith, I'm not talking about the timing causing a different mapping, I'm saying that because both processes are sharing stdout, the output may show an "old" value.